After many discussions with fellow web developers, I've decided it is best to have a per page style sheet. This article contains my Wordpress plugin which will check to see if the current page has it's own style sheet.

The Steps To Install

  • Copy the below text into a file and name it per-page.php (anything.php will work). Or download
  • Move the file into your plugins directory of your Wordpress install.
  • Log in to your WP-Admin and active CSS-PER-PAGE-NIX
  • In your theme/styles directory create a "pages" directory (/themes/styles/pages/)
  • In the header of your theme add the following line where you want the style sheet included.
<?php echo insert_page_styles(); ?>

This plugin inserts the line

<link rel="stylesheet" href="/your/path/to/page/style" type="text/css" media="screen" /> 
into your header. Instead of just blindly posting the style sheet, this plugin checks to see if the actual style sheet for the current page, so you don't get a pesky 404.

Name all of your pages after the slug with the .css extension.

The Code

<?php
/*
Plugin Name: CSS-PER-PAGE-NIX
Plugin URI: http://www.nickyeoman.com/blog/wordpress/70-wp-css-page
Description: Takes the last url segment and servers style sheets based on that.
Version: 1.1
Author: Nick Yeoman
Author URI: http://www.nickyeoman.com
*/

/**
* Call this function from your template
* Parameters:
* css_path is path from url root.  Full path will work too.
**/
function insert_page_styles() {
  //set link to return
  $link = null;
  //you need a /styles/pages in your theme
  //TODO: Create this automatically during install.
  $css_path = "/styles/pages/"; 
  
  //get segment
  //TODO: just grab the last array item no point in looping through
  foreach (explode("/",$_SERVER["REQUEST_URI"]) as $segment) {
    if (trim($segment) != "")
      $slug = $segment;
  }

  //Get full path of file
  $path = get_theme_root() . "/" . get_template() . $css_path;
  $filename = $slug . ".css";
  $fullpath = $path . $filename;
  
  //check if page exists
  if (file_exists($fullpath)) {
    $blogpath = get_bloginfo('template_url'); //get url
    $urlpath = $blogpath . $css_path . $filename;
    $link =<<<EOHTML
      <link rel="stylesheet" href="$urlpath" type="text/css" media="screen" />
EOHTML;
  }
  return $link;
}
?>

If anyone has optimisation tips or has a better way of doing this, please contact me I'd love to hear from you.