I want to load a .js file from my custom plugin into the section of my wordpress installation. If I use the function file_get_contents and than echo this string output, it will be placed into body alltime. It should be placed in the head.
$headScript = new headScript();
$headScript->stipsHead();
My Head class
class headScript
{
private string $scriptPath = 'assets/myFrontendScript.js';
function stipsHead() {
add_action('wp_head', array($this, 'getScript'));
}
function getScript() {
wp_enqueue_script('js-file',BASE_PATH . $this->scriptPath);
}
it should be in the head?. Same results come out with echo file_get_contents().
How I can put myFrontendScript.js in the header of my wordpress instance?
CodePudding user response:
I think this is what you are looking for. You can let Wordpress handle the loading, if you use wp_enqueue_script()
:
add_action( 'wp_enqueue_scripts', [ $this, 'my_wp_enqueue_scripts' ], 100 );
/**
* Load the Javascript file
*/
function my_wp_enqueue_scripts() {
$theme = wp_get_theme();
$file_with_path = get_template_directory() . '/some/path/script.js';
wp_enqueue_script( 'my-scripts', $file_with_path, '', $theme->Version, false );
}
Assuming the template that is in use, was developed "correctly" to the Wordpress standard, you should then see your script in the header.