I'm trying to enqueue a JS file (located at /js/example-script.js), just to get an alert on page load.
Can anyone tell me what I'm doing wrong?
In my example-script.js:
jQuery(document).ready(function($) {
alert("hi");
});
And in my functions file:
function my_theme_scripts() {
wp_enqueue_script( 'example-script', get_template_directory_uri() . '/js/example-script.js', array( 'jquery' ), '1.0.0', true );
}
add_action( 'wp_enqueue_scripts', 'my_theme_scripts' );
jQuery is loaded in my sources, so that's not the problem...
I'm trying to enqueue a JS file (located at /js/example-script.js), just to get an alert on page load.
Can anyone tell me what I'm doing wrong?
In my example-script.js:
jQuery(document).ready(function($) {
alert("hi");
});
And in my functions file:
function my_theme_scripts() {
wp_enqueue_script( 'example-script', get_template_directory_uri() . '/js/example-script.js', array( 'jquery' ), '1.0.0', true );
}
add_action( 'wp_enqueue_scripts', 'my_theme_scripts' );
jQuery is loaded in my sources, so that's not the problem...
I would recommend using wp_enqueue_script with get_theme_file_uri this allows child themes to overwrite this file.
get_theme_file_uri() function
Searches in the stylesheet directory before the template directory so themes which inherit from a parent theme can just override one file.
wp_enqueue_script( 'example-script', get_theme_file_uri( '/js/example-script.js' ), array('jquery'), null, true );
wp_enqueue_script( 'example-script', plugins_url('/js/example-script.js', __FILE__), array(), null );
Are you using a child theme ? In this case you have to use get_stylesheet_directory_uri()
instead of get_stylesheet_template_uri()
which returns the parent theme uri
https://developer.wordpress/reference/functions/get_template_directory/#usage
All answers correct - in my case I'd done it right, just wasn't loading the WP Footer, despite jQuery showing in my sources. As soon as I added in get_footer(), all worked fine.
example-script
handler name – Pratik Patel Commented Dec 20, 2018 at 11:02