Why isn't enqueued script in wordpress working

2019-08-31 18:37发布

问题:

I have a Wordpress childtheme using a functions.php that contains the following:

    <?php
        add_action( 'wp_enqueue_scripts', 'load_custom_script' ); 
        function load_custom_script() { 
        wp_register_script( 'custom-script', get_template_directory_uri() . '/js/wpw-custom.js',   array('jquery'), '1.0', true ); 
        wp_enqueue_script( 'custom-script' );
      }
   ?>

This is successfully loading my custom script, in the footer, AFTER jQuery itself loads. The custom script contains the following testing code to let me know if the enqueue process works:

$( document ).ready(function() {
alert( "ready!" );
});

I can view source on my pages and verify the successful loading of my wpw-custom.js but it is not executing the alert!

What have I done wrong or what steps can I take to methodically find out what I have done wrong? Many thanks for any help!

回答1:

jQuery in WordPress runs in noConflict mode which means the global $ shortcut for jQuery isn't available. Replace your code with the following:

jQuery(document).ready(function($) {
    alert( 'ready!' );
});

Inside the document ready wrapper the $ can be used as an alias for jQuery.