Back to Top

Enqueue Style Sheets with Conditional Statements

Previous Post:

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:

  1. <!--[if IE]>
  2.     <link rel="stylesheet" type="text/css" href="ie-only.css" />
  3. <![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:

  1. function bwp_enqueue_styles()
  2. {
  3.     global $wp_styles;
  4.     // other style sheets...
  5.     // ie-only style sheets
  6.     wp_register_style('all-ie-only', get_bloginfo('stylesheet_directory') . '/css/ie-only.css');
  7.     $wp_styles->add_data('all-ie-only', 'conditional', 'IE');
  8.     wp_enqueue_style('all-ie-only');
  9. }
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:

  1. <!--[if IE]>
  2. <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' />
  3. <![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

  1. http://codex.wordpress.org/Function_Reference/get_blogi ... t_bloginfo []
  2. http://codex.wordpress.org/Function_Reference/wp_regist ... ster_style []
Elegant Themes - Designed with Modest Elegance
Print Article Trackback Trackback to this Article   Subscribe to Comments RSS Subscribe to Comments RSS
 Sponsor   Themes by Elegant Themes - $39 for unlimited access to 80+ WordPress Themes!

Speak Up Your Mind!

An asterisk (*) indicates a required field and must be filled.




  • Web page and e-mail addresses turn into links automatically.
  • Wrap codes in: <code lang=""></code> or <pre lang="" extra="">
  • Lines and paragraphs break automatically.

Next Post: