Gordonmac Dot Com

Mostly a web development blog

Enqueue IE Conditional Scripts and Styles in WordPress

Posted: January 20th, 2016 | Tags: | Posted in: PHP, Tutorials, Wordpress
Note: This tutorial was originally published in 2016. The tips and techniques explained may be outdated.

If you’re like me, and prefer to load all styles and scripts using wp_enqueue_style and wp_enqueue_script there’s quite an elegant way to do this in WordPress.

First, in your functions.php (or however you organise theme files) create an array of the conditional scripts you wish to include:

$conditional_scripts = array(
	'html5shiv' => get_template_directory_uri() . '/vendor/html5shiv/html5shiv.min.js',
	'respond' => get_template_directory_uri() . '/vendor/respond/respond.min.js',
	'selectivizr' => get_template_directory_uri() . '/vendor/selectivizr/selectivizr-min.js'

Now loop through the array adding wp_enqueue_script at each iteration:

foreach ( $conditional_scripts as $handle => $src ) {
	wp_enqueue_script( $handle, $src, array(), '', false );

Finally, add a filter to add the IE proprietary conditional comments:

add_filter( 'script_loader_tag', function( $tag, $handle ) use ( $conditional_scripts ) {

	if ( array_key_exists( $handle, $conditional_scripts ) ) {
		$tag = '<!--[if (lt IE 9) & (!IEMobile)]>'. $tag .'<![endif]-->'."\n";
	return $tag;
}, 10, 2 );

That’s all. Hopefully one day in the near future we won’t need to do things like this.