Add CSS or Javascript to WordPress head for specific pages

Often I find myself needing to add a lot of extra styling to one or two pages in WordPress but I don’t want to bloat my theme’s style.css with lots of extra code.

With a simple PHP switch I can add additional CSS, Javascript or other items to the page head.

First create a file in your theme called header-page-includes.php. Then add a switch statement and a case for each page that you want to add custom CSS or Javascript to:

if(is_page()) {
  switch (get_the_title()) {
    case "About":
      echo '<link rel="stylesheet" type="text/css" href="'.get_bloginfo( 'template_url' ).'/css/about.css" />';
        break;
    case "FAQ":
      echo '<link rel="stylesheet" type="text/css" href="'.get_bloginfo( 'template_url' ).'/css/faq.css" />';
      echo '<script src="'.get_bloginfo( 'template_url' ).'/js/faq.js"></script>';
      break;
  }
}

I chose to evaluate the page title, but if you have multiple page titles that are the same you may want to use the page ID instead.

Then include that file in your header.php

get_template_part('header-page-includes');

Pros

  • Maintain page-specific CSS and Javascript without a plugin
  • Ability to reuse CSS and Javascript for multiple pages

Cons

  • Your switch statement could get long and difficult to maintain. I suggest keeping your pages in alphabetical order.

About Seth

Digital marketer and web professional from Des Moines, IA.

1 Comment

  1. Buffy on October 5, 2011 at 4:51 pm

    Hey hey hey, take a gadner at what you’ve done

Leave a Comment