If you use a lot of different stylesheets for your theme, it can get a little tedious to add them all to your header.php file. You could import them in your style.css, but some of the great minification plugins do not support import.

If you organize all your stylesheets in a sub-folder in your theme, you can use the below function to automatically register and add them to your theme, provided that you use the wp_head() function in the head section of your header.php.

Usage:

  • Add the below code to your functions.php file in your theme folder.
  • Add your stylesheets to a sub-folder named css.
  • You can add a print stylesheet, by calling it print.css, for a good starting point, try out Hartija.
  • For handheld devices, you can add a stylesheet called either iphone.css or handheld.css.
  • Lastly you can add a stylesheet for projection, and yes it should be called projection.css.
  • All the above stylesheets should be placed in the CSS folder.
  • If you want to use a different location for your stylesheets, you can change the location in the last part of the themeCSSUrl and themeCSSDir variables, to point to your desired location.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<?php
add_action('wp_print_styles', 'add_stylesheets');
 
function add_stylesheets() {
  $themeCSSUrl =  get_stylesheet_directory_uri() . '/css/';
  $themeCSSDir = dirname(__FILE__). '/css/';
  if ($handle = opendir($themeCSSDir)) {
    while (false !== ($file = readdir($handle))) {
      if(end(explode(".",$file))=='css') {
        if($file=='print.css') {
          wp_register_style(current(explode(".",$file)), $themeCSSUrl.$file,array(),'0.8','print');
          wp_enqueue_style( current(explode(".",$file)));
        } elseif($file=='handheld.css' || $file=='iphone.css') {
          wp_register_style(current(explode(".",$file)), $themeCSSUrl.$file,array(),'1.0','handheld');
          wp_enqueue_style( current(explode(".",$file)));
        } elseif($file=='projection.css') {
          wp_register_style(current(explode(".",$file)), $themeCSSUrl.$file,array(),'1.0','projection');
          wp_enqueue_style( current(explode(".",$file)));
        } else {
          wp_register_style(current(explode(".",$file)), $themeCSSUrl.$file,array(),'1.0','screen');
          wp_enqueue_style( current(explode(".",$file)));
        }
      }
    }
  }
}
?>

Update 8/4-2011
changed get_bloginfo('template_url') to get_stylesheet_directory_uri() to make this work for child themes as suggested by Paul.