WordPress – jQuery

WordPress will load jQuery automatically without you having to add the files yourself. I’ve seen a different methods, some of which do not always work. Here’s the method I use that seems to work reliably.

The following would be added to your functions.php file. If you don’t have a functions.php yet, create one, in your theme folder.

 

<?php 
function theme_init() {
	if (!is_admin()) {
		wp_enqueue_script('jquery');
	}
}
add_action('init', 'theme_init');

 

Note! There can be no characters, this include spaces, or extra lines, in front of the tag. This is good practice. Extra characters outside of the php tag will cause the server to create HTTP header and send it to the browser before WordPress is ready.

If you already have a funtions.php file in your theme, you can add the snippet above, without the <?php.

WordPress loads jQuery in “No Conflict” mode. This means that jQuery will be accessed through the variable jQuery rather than the $. To work with this easily, set up your document ready actions like this:

jQuery(function($){ // Notice the $ here!
	$("#box>div>div").eq(0).siblings().hide();
	$("#box>ul>li.slide-thumb").click(function(event){
		var index = $(this).index();
		$("#box>div>div.slides").fadeOut(400).eq(index).fadeIn(400)
	});
});

Notice here, that jQuery (note the uppercase Q!) replaces the $ outisde the ready function. While inside the function I’ve used the $. This is possible by including the $ as a parameter to the function inside jQuery(function($){}). Placing this variable here allows jQuery to assign itself to this name, so inside of the function you can use that variable in place of jQuery.

Leave a Reply

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