How to use custom jQuery / javascript in WordPress, the right way!

This article was written by in August 5, 2013, & may not be posted on other sites!
Original source url for this article: How to use custom jQuery / javascript in WordPress, the right way!

How to add custom jquery in WordPress, the right way.
The normal way of adding custom javascript and jQuery may conflict with plugins or theme functions in a WordPress website. Don’t use the <script> tag in the <head> to add external jQuery or javascript files to your WordPress site as you normally would in html. This is how to add custom javascript or jQuery in WordPress, the right way:

  1. First of all, you should always work with a childtheme or a custom theme in WordPress to avoid problems when updating (may cost overwrite) and conflicts.
  2. Open your wordpress themes file functions.php in a text editor or in wordpress admin appearance > editor. If you don’t have a functions.php file, create one and put it directly into your theme folder.
  3. Create a js-file and put it somewhere in your custom theme folder.
  4. Add this code in your functions.php to enable the WordPress local jQuery library and activate your custom js file:
    <?php
    function my_init() {
    if (!is_admin()) {
    wp_deregister_script('jquery');// load the local copy of jQuery
    wp_register_script('jquery', '/wp-includes/js/jquery/jquery.js', false, '1.3.2', true);
    wp_enqueue_script('jquery');
    //load your own custom js
    wp_enqueue_script('my_script', 'http://www.yoursite.com/wp-content/themes/your_custom_theme/js/custom-jquery.js', array('jquery'), '1.0', true);
    }
    }
    add_action('init', 'my_init');?>
  5. Make sure you have the right url to your custom jQuery or javascript file.
  6. To load multiple scripts just add more wp_enqueue_script:
    wp_enqueue_script(‘second_script’, ‘your_path_url/js02.js’, array(‘jquery’), ’1.0′, true);
    wp_enqueue_script(‘third_script’, ‘your_path_url/js03.js’, array(‘jquery’), ’1.0′, true);
  7. If you are working with jQuery in your js-file should have a good base (inside your jQuery file), something like this:
    jQuery(function ($) {
        $( document ).ready(function() {
           //your js code goes here
        });
    });

    This let’s you use the $ character as you normally would in jQuery instead of writing out the word “jQuery”.

Rock on!

How to use custom jQuery / javascript in WordPress, the right way!

Spread the word

Facebooktwittergoogle_pluslinkedinmail

Leave a Reply

Your email address will not be published. Required fields are marked *