I have been trying to use wp_enqueue_script() to load a JS script into one of my pages but it keeps throwing a "Failed to load resource" 404 error in the console (running Chrome). My code is as follows:
myplugin.php:
function myplugin_load_script() {
wp_enqueue_script( 'myplugin-testjs', (plugin_dir_path( __FILE__ ) . "scripts/myplugin-test.js"), array('jquery'), null, true );
add_action('wp_enqueue_scripts', 'myplugin_load_script');
}
myplugin-test.js:
alert("Hello!");
I have checked the HTML tag and the development tools and both of them display the correct URL (eg. wp-content/plugins/myplugin/scripts/myplugin-test.js).
I have also checked that the file does exist there and the name is correct, PHP throws no errors either. Thanks for any help!
I have been trying to use wp_enqueue_script() to load a JS script into one of my pages but it keeps throwing a "Failed to load resource" 404 error in the console (running Chrome). My code is as follows:
myplugin.php:
function myplugin_load_script() {
wp_enqueue_script( 'myplugin-testjs', (plugin_dir_path( __FILE__ ) . "scripts/myplugin-test.js"), array('jquery'), null, true );
add_action('wp_enqueue_scripts', 'myplugin_load_script');
}
myplugin-test.js:
alert("Hello!");
I have checked the HTML tag and the development tools and both of them display the correct URL (eg. wp-content/plugins/myplugin/scripts/myplugin-test.js).
I have also checked that the file does exist there and the name is correct, PHP throws no errors either. Thanks for any help!
Share Improve this question edited Oct 5, 2017 at 8:26 cybmeta 20.6k5 gold badges47 silver badges57 bronze badges asked Oct 5, 2017 at 7:57 JuckixJuckix 131 silver badge3 bronze badges1 Answer
Reset to default 2Your syntax is wrong. The action must be defined outside of the callback.
Also, you are using plugin_dir_path()
function, which gets the path to plugin directoy in the filesystem of the server, not the url. You should use plugin_dir_url()
instead.
add_action( 'wp_enqueue_scripts', 'myplugin_load_script' );
function myplugin_load_script() {
wp_enqueue_script( 'myplugin-testjs', plugin_dir_url( __FILE__ ) . "scripts/myplugin-test.js", array('jquery'), null, true );
}