In a WordPress theme, how do you conditionally include scripts for ie8 and below? This is primarily to apply polyfills for various html5/css3 features. I see that wp has the $is_IE variable which can be used as a conditional to only include scripts for IE. Is there a way to add the script for only certain versions of IE though rather than all of them? This is simple with some HTML ie conditional comments, but I’d like to include the scripts all in the same place in my functions file.
Conditional for specific versions in HTML:
<!--[if lt IE 9]> <script src="iepolyfill.min.js"></script> <![endif]-->
Conditional for all IE in WP:
global $is_IE;
if ( $is_IE ) {
wp_enqueue_script( 'iepolyfill', bloginfo('stylesheet_directory').'/js/iepolyfill.min.js' );
}
I’ve looked around and mainly find details about conditional scripts for wp backend only.
Any suggestions?
For WordPress 4.2+
Use
wp_script_add_data
to wrap the script in a conditional comment:Just make sure you register the script before invoking
wp_script_add_data
(registering is handled bywp_enqueue_script
above), and that the first argument you pass towp_script_add_data
matches the first argument you passed when you registered the script.For WordPress 4.1
You can use the
script_loader_tag
filter today to enqueue scripts wrapped in conditional comments. Hereâs an example implementation:And if you want to include more than one script in the same way, you can use something like:
wp_register_script()
whenever you add scripts to your WP themes or plugins.For IE, conditional tags work very well. Here’s how you can add conditional tags into a script, example is for HTML5shiv:
Solution for WordPress 4.2 and above
The correct way would be to apply wp_enqueue_script since it JavaScripts here, and not css styles. Also, it is better to use get_bloginfo(‘stylesheet_url’) to make sure this also works in Child Themes.
Update for WordPress 4.7.3 with scripts loading from CDN:
The best way to do it is enqueue the scripts and then use wp_style_add_data() to put conditional. This method is being used by official themes like twenty thirteen
There is an answer similar to this but he adds extra if in the condition which is wrong.
As wordpress is a PHP script, it can access server variable via $_SERVER
Then you can search for detect browser with PHP, PHP: If internet explorer 6, 7, 8 , or 9
Try to use the
wp_style_add_data()
function (officially used in twentythirteen and twentyfourteen theme:Update: Since WordPress >= 4.2.0 there is a function that is used in the same way. It’s called: