Enqueue Style Sheets with Conditional Statements
Have you ever needed the ability to add a conditional style sheet using WordPress’s enqueuing system? You know, to deal with the dreadful Internet Explorer 6?
The popular function wp_enqueue_style() doesn’t allow you to do this at all but the core WordPress actually has that feature. You will be able to add something like this:
- <!--[if IE]>
- <link rel="stylesheet" type="text/css" href="ie-only.css" />
- <![endif]-->
<!--[if IE]> <link rel="stylesheet" type="text/css" href="ie-only.css" /> <![endif]-->
to your theme’s header. To make that happen, in the main function you use to enqueue your style sheets, for example bwp_enqueue_styles(), just add this when enqueuing ie-only.css:
- function bwp_enqueue_styles()
- {
- global $wp_styles;
- // other style sheets...
- // ie-only style sheets
- wp_register_style('all-ie-only', get_bloginfo('stylesheet_directory') . '/css/ie-only.css');
- $wp_styles->add_data('all-ie-only', 'conditional', 'IE');
- wp_enqueue_style('all-ie-only');
- }
function bwp_enqueue_styles()
{
global $wp_styles;
// other style sheets...
// ie-only style sheets
wp_register_style('all-ie-only', get_bloginfo('stylesheet_directory') . '/css/ie-only.css');
$wp_styles->add_data('all-ie-only', 'conditional', 'IE');
wp_enqueue_style('all-ie-only');
}Please note the use of get_bloginfo()1 and wp_register_style()2 to properly enqueue your style sheet.
Now if you look at the <head> section of your website/blog you should see this:
- <!--[if IE]>
- <link rel='stylesheet' id='all-ie-only-css' href='http://example.com/path-to-css/css/ie.css?ver=3.1' type='text/css' media='all' />
- <![endif]-->
<!--[if IE]> <link rel='stylesheet' id='all-ie-only-css' href='http://example.com/path-to-css/css/ie.css?ver=3.1' type='text/css' media='all' /> <![endif]-->
Pretty neat!
References
- http://codex.wordpress.org/Function_Reference/get_blogi ... t_bloginfo [↩]
- http://codex.wordpress.org/Function_Reference/wp_regist ... ster_style [↩]







Recent Opinions