How do I add a simple jQuery script to WordPress?

后端 未结 18 1704
心在旅途
心在旅途 2020-11-22 16:53

I read the Codex and a few blog posts about using jQuery in WordPress, and its very frustrating. I\'ve got as far as loading jQuery in functions.php file, but a

18条回答
  •  清酒与你
    2020-11-22 17:38

    After much searching, I finally found something that works with the latest WordPress. Here are the steps to follow:

    1. Find your theme's directory, create a folder in the directory for your custom js (custom_js in this example).
    2. Put your custom jQuery in a .js file in this directory (jquery_test.js in this example).
    3. Make sure your custom jQuery .js looks like this:

      (function($) {
      $(document).ready(function() {
      $('.your-class').addClass('do-my-bidding');
      })
      })(jQuery);
      
    4. Go to the theme's directory, open up functions.php

    5. Add some code near the top that looks like this:

      //this goes in functions.php near the top
      function my_scripts_method() {
      // register your script location, dependencies and version
         wp_register_script('custom_script',
         get_template_directory_uri() . '/custom_js/jquery_test.js',
         array('jquery'),
         '1.0' );
       // enqueue the script
        wp_enqueue_script('custom_script');
        }
      add_action('wp_enqueue_scripts', 'my_scripts_method');
      
    6. Check out your site to make sure it works!

提交回复
热议问题