Pregunta

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!

¿Fue útil?

Solución

Your 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 );

}
Licenciado bajo: CC-BY-SA con atribución
scroll top