How to WP Enqueue Script or Style Only for Internet Explorer

In WordPress we use wp_enqueue_script and wp_enqueue_style functions to add our script and stylesheet to the page. By default these functions print <script> and <link> tags as normal. But sometimes we need to print our script/link tag inside html conditional comments specially for Internet Explorer.
For example we want to print following HTML

<link rel="stylesheet" href="my-style.css" >
<!--[if IE]>
<link rel="stylesheet" href="my-style-ie.css" >
<![endif]-->

<script type="text/javascript" src="js/my-script.js"></script>
<!--[if IE]>
    <script type="text/javascript" src="js/my-script-ie.js"></script>
<![endif]-->

Here is my solution to enqueue script or style inside conditional comments

<?php

//Adding stylesheets
wp_register_style('my_style','/js/my-style.css');
wp_register_style('my_style_ie','/js/my-style-ie.css');

//add the condition here
//You can change condition string 'IE' to 'IE 6' , 'IE 7' etc.
wp_style_add_data( 'my_style_ie', 'conditional', 'IE' );

wp_enqueue_style( 'my_style' );
wp_enqueue_style( 'my_style_ie' );

//Adding scripts
wp_register_script('my_script','/js/my-script.js');
wp_register_script('my_script_ie','/js/my-script-ie.js');

//add the condition here
//You can change condition string 'IE' to 'IE 6' , 'IE 7' etc.
wp_script_add_data( 'my_script_ie', 'conditional', 'IE' );

wp_enqueue_script( 'my_script' );
wp_enqueue_script( 'my_script_ie' );

?>

Leave a Reply

Your email address will not be published. Required fields are marked *

 

This site uses Akismet to reduce spam. Learn how your comment data is processed.