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.
Maybe in the next version of Wordpress ;)
Thanks for the snippet. What would be Wordpress without you? :)
I use this:
if ( !is_admin() ) :
wp_deregister_script( ‘jquery’ );
wp_register_script( ‘jquery’, ( ‘http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js’ ), false, ’1.4.1’, false );
//wp_enqueue_script( ‘jquery’ );
endif;
Which force unloads without looking to see if what’s being force unloaded is newer.
Awesome, Michael!
I don’t suppose there’s a way to keep this fully dynamic and always grab the latest version of jQuery? I have themes in mind. And pushing out updates to simply update the version of jQuery that’s bundled isn’t exactly efficient.
It’s also not necessary most of the time, but for the sake of argument, you could simply load it off your own server or something like that, though that’s a bit ugly. Beyond that I supposed you could set up some sort of system to check for updates on your (or jQuery’s) server and auto-download them when they become available. Though I think that may be a bit much.