Using jQuery in WordPress

Loading the jQuery that comes with WordPress

Add this PHP code to header.php before wp_head()

<?php wp_enqueue_script( 'jquery' ); ?>

What not to do – Using a Google served jQuery instead

Add this PHP code to functions.php but make sure it’s the latest version.

<?php function my_scripts_method() {
    wp_deregister_script( 'jquery' );
    wp_register_script( 'jquery', 'http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js');
    wp_enqueue_script( 'jquery' );
}    

add_action('wp_enqueue_scripts', 'my_scripts_method'); ?>

Adding your own jQuery

Wrap your jQuery in the following to use the default jQuery shortcut of $ instead of the jQuery that Wordpess uses to avoid conflicts. Note this must go after wp_head() and you may need to use type="text/javascript" in the script tags if you’re not using HTML5.

<script>
    jQuery(document).ready(function($) {
        $('#site-title').addClass('Testing');
    });	
</script>

$() will work as an alias for jQuery() inside the function above.

Leave a Reply

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