Add jQuery to your Theme or Plugin

I often use jQuery in the Themes and, without exception, in all the Plugins I write. You can easilly add jQuery to any HTML-document by simply linking to Googles jQuery-script, but this is not always without problems, especially if your sites employs several libraries.

jQuery is often added with this line between and <head> and </head>:

<script type="text/javascript" src="http://jqueryjs.googlecode.com/files/jquery-1.3.2.js"</script>

But this can – among other things – cause latency in page loading, and is really not necessary as WordPress comes pre-packed with a lot of script-libraries, including jQuery.

To add jQuery (or Script-A-Licious or ProtoType) to your Theme, you simply use the wp_enqueue_script() function. In your Themes functions.php (if it doesn’t exists, simply create it) you add these lines:

<?php
function yourtheme_init(){
 wp_enqueue_script('jquery');
 wp_enqueue_script('jquery-ui-core');
}
add_filter('wp_enqueue_scripts', 'yourtheme_init');
?>

This will load jQuery on your site’s frontend. If you have plugins that use jQuery, the upshot of this method is that WP will not load jQuery multiple times (as it will if you add it manually to your Theme), and thus not cause conflicts.

To avoid jQuery conflicts you should also surround your scripts with this:

<script type="text/javascript">
jQuery.noConflict();
jQuery(document).ready(function($){

YOUR SCRIPT HERE

});
</script>

Leave a Reply

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