Enqueue different and/or multiple versions of jQuery in WordPress

Adapted from past work and this article on WP Engine’s blog.

add_action( 'wp_enqueue_scripts', 'pp_custom_scripts_enqueue' );
function pp_custom_scripts_enqueue() {

	$theme = wp_get_theme(); // Get the current theme info for version numbers

	// The default WordPress version of jQuery is left to enqueue as intended.

	// Register and inline a second specific version of jQuery
	wp_register_script( 'jquery3.2.1', 'https://code.jquery.com/jquery-3.2.1.min.js' );
	wp_add_inline_script( 'jquery3.2.1', 'var jQuery3_2_1 = $.noConflict(true);' );

	// Register custom scripts with dependency on the default WordPress jQuery version
	wp_register_script( 'js_main', get_stylesheet_directory_uri().'/scripts/js_min.js', array( 'jquery' ), $theme['Version'], true); // Register a script with dependencies and version in the footer

	// Register custom scripts with dependency on the specific version of jQuery we enqueued
	wp_register_script('js_main_custom_version', get_stylesheet_directory_uri().'/scripts/js_min_custom_version.js', array('jquery3.2.1'), $theme['Version'], true); // Register a script with dependencies and version in the footer

	// Enqueue registered scripts
	wp_enqueue_script('js_main');
	wp_enqueue_script('js_main_custom_version');

	// Localize scripts
	$localize_var_args = array(
		'site_title' => get_bloginfo('name'),
		'home_url' => home_url(),
		'theme_url' => get_stylesheet_directory_uri(),
		'ajaxurl' => admin_url( 'admin-ajax.php' )
	);
	wp_localize_script( 'js_main', 'wp_js_vars', $localize_var_args );

}

Revisions

Tags: ,

No comments yet.

Leave a Reply