How to load jQuery correctly in WordPress and not get any conflicts.

I finally had my aha moment with jQuery and WordPress themes. I used to think one would want to deregister the WordPress jQuery that comes with your WordPress installation, then enqueue Google’s version so that sites would load faster. I have finally decided against this as it leads to too many conflicts with potential plugins.

Here is what you should be doing instead. How to load jQuery in WordPress correctly and not get any conflicts as well as how to load other jQuery custom files and what you should do to have them load correctly.

First, to include jQuery and other custom scripts in your theme, you simply enqueue the latest jQuery and your other scripts like this:

 // Enqueueing all the java script in a no conflict mode
 function ineedmyjava() {
	if (!is_admin()) {
 
		// Include jQuery included with WordPress
		wp_enqueue_script( 'jquery' );
		
		// Custom Theme scripts...
		wp_register_script(
			'custom',
			get_bloginfo('template_directory') . '/js/custom.js',
			array('jquery') );
		wp_enqueue_script('custom');
		
		// Homepage slider 'flexslider' scripts...
		wp_register_script(
			'flexslider',
			get_bloginfo('template_directory') . '/js/flexslider.js',
			array('jquery') );
		wp_enqueue_script('flexslider');
		
		// Add more
		
		
		// between here
		
	}
}
 
add_action('wp_enqueue_scripts', 'ineedmyjava');

Ok, so that loads your jQuery, your custom jQuery scripts, and your flexslider in the example above. So how do you set up your custom scripts so they actually work?

Here’s how:

If you’re loading the above scripts in your header, put all your custom scripts between the document ready function like this:

/**
 *	Custom jQuery Scripts
 *	
 */
jQuery(document).ready(function($){
	
	// All your custom scripts here
	
	// front page slider 
	$('.flexslider').flexslider({
		animation: "slide",
	}); // end register flexslider
	
	
});// END #####################################    END

But if you decide to load them in the footer, include them like this:

/**
 *	Custom jQuery Scripts
 *	
 */
(function($){
	
// All your custom scripts here
	
	// front page slider 
	$('.flexslider').flexslider({
		animation: "slide",
	}); // end register flexslider

}(jQuery));// END

And there you have it. No conflicts…