Dane. Designer.

Old Blog

How To Load the Latest Version of jQuery in WordPress

While WordPress ships with jQuery, it’s often a few updates behind the latest version. Since jQuery 1.4 is just out, I wanted to use it with K2. That in and of itself is fairly easy, and a simply matter of deregistering the ‘jquery’ script and registering a new one. While looking for a proper solution I came across this rather crude way of going about it quite a lot, and it’s a horribly way of going about this, and will (and has probably) undoubtedly result in old plugins and themes blindly overwriting newer version of jQuery with their own, once new hotness, now old and busted version of jQuery.

Ugh.

This PHP code snippet checks to see if the passed version is later than the one currently registered, and makes sure we’re not in the admin (just to be sure).

If our version is indeed newer than the one currently registered, we go ahead and grab the idol… eh, swap jQuery’s.

/**
 * Register a later version of jQuery if it’s later than the one currently in WordPress
 *
 * @param {String} our_version The version of jQuery we want to upgrade to if needed.
 */
function upgrade_jquery( our_version ) {
	// We want to use the latest version of jQuery, but it may break something in
	// the admin, so we only load it on the actual site.
	global $wp_scripts;

	if ( ( version_compare(our_version, $wp_scripts -> registered[jquery] -> ver) == 1 ) && !is_admin() ) :
	 	wp_deregister_script(‘jquery’); 

	 	wp_register_script(‘jquery’,
			get_bloginfo(‘template_directory’) . ‘/js/jquery.js’,
			false, our_version);
	endif;
}

add_action( ‘wp_head’, upgrade_jquery( ’1.4.1’ ) );

It sure would be neat if this was built straight into WordPress’ wp_register_script.