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:


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




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!


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

  • May I ask why the action needs to be above the function definition? I also don't quite understand the difference between the path and the dir functions, in the browser console the <script> tag looks identical to the previous one.
    – Juckix
    Oct 5 '17 at 8:34
  • Okay I actually missed the edit. The add_action() was meant to be outside of the function, after the closing curly bracket. My question on the path/dir difference still stands.
    – Juckix
    Oct 5 '17 at 8:45
  • The add_action() needs to be outside the callback (function) your are defining for the action, either above or bellow it is your choice, but not inside the callback. The path in the filesystem is the location of the file/dir in the machine. For example, in an Apache server it tipically looks like /home/user/public_html/wp-content/plugins/my-plugin/. In a Windows PC it may looks like C:\users\dir. If you got a identical value for dir path and dir url, I guess you just was lucky.
    – cybmeta
    Oct 5 '17 at 9:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.