Adding jQuery to WordPress

Glenn Glenn's Blog 0 Comments

Adding jQuery to WordPress Adding jQuery to WordPress jquery workshop

First off WordPress comes loaded with a selection of scripts and these can be found in the wp-includes/js/ directory. WordPress already uses jQuery in the admin area and so it’s already native and can be called easily by the following line of code in your header.php file in the <head> section:

<?php wp_enqueue_script("jquery"); ?>
<?php wp_head(); ?>

Now you may well already have the ‘wp_head’ function in your header.php file and so you must simply ensure that you call the ‘wp_enqueue’ script before that.

Problems with this method

We’ve encountered a few problems with this method and the main are that:-

1. It simply doesn’t work on all themes
2. It doesn’t necessarily give you the latest version of jQuery direct from WordPress

Solution

Reference jQuery (the right way) from within WordPress. This time we are going to edit the functions.php file and simply add the following lines of code:-

<?php
function my_init_method() {
wp_deregister_script( 'jquery' );
wp_register_script( 'jquery', 'http://code.jquery.com/jquery-latest.js');
}
add_action('init', 'my_init_method');
?>

You can see that what we are doing here is bypassing the jQuery from WordPress and accessing an external version from the jQuery code repository. We prefer this repository as it readily gives us the latest version but you could equally use that of Google e.g. ‘http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js’

Still More Problems?

Then you can still reference jQuery from the <head> of your header.php file like so:-

<script type="text/javascript" src="https://code.jquery.com/jquery-latest.js"></script><!--latest jQuery -->

or

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
About the Author
Adding jQuery to WordPress Adding jQuery to WordPress 0da77002febbfe28d15144a57bbcc2c9 s 180 d mm r g

Glenn

A highly experienced WordPress Web Developer, Front-end and Back-end Developer & New Media Specialist with extensive knowledge of a wide spectrum of technologies in the Development and Creative Industries built up over a number of years.

Leave a Reply

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


*