Rin
Rin

Reputation: 43

How can I link a JS script to my header file?

I want to add a JS script with jQuery to the header file in Wordpress. It's function is to darken the background of an element representing a page everytime someone clicks on it.

I've tried adding it with plugins and via functions.php file. Neither way worked. I inserted a code into functions.php on my child theme which caused my page to not work at all, even after removing the code, so I had to recover the site with a backup. After that I added a fuction with wp_enqueue_script which didn't work either. Luckily after removing the code my site worked again. I didn't add it via header.php file itself because I read that it might cause problems for the website.

So my question is: Is there any way to link a JS script to header.php? Maybe without using functions.php?

Edit: Added the code used for functions.php

function my_theme_scripts_function() {

wp_enqueue_script( 'myscript', get_stylesheet_directory_uri() . '/js/myscript.js');

}

add_action('wp_enqueue_scripts','my_theme_scripts_function');

I replaced get_template_directory_uri() with get_stylesheet_directory_uri() since I'm adding this to a child theme. I got it from this tutorial: https://www.collectiveray.com/wp/tips/add-javascript-to-wordpress

Upvotes: 0

Views: 258

Answers (1)

hellheim
hellheim

Reputation: 71

You should use functions.php file of your child theme to prevent an update overwriting your changes.

Answering your question, wp_enqueue_script - look at the 5th argument $in_footer, it must be set to true, thus your script will be loaded in header.

wp_enqueue_script( string $handle, string $src = '', array $deps = array(), string|bool|null $ver = false, bool $in_footer = false )

Upvotes: 1

Related Questions