Adding custom CSS to a wordpress blog post

In the previous post, I showed how to create fancy mouseover buttons in wordpress without having to resort to the ugliness  javascript. However, the post finished up with one very big issue….. You can’t include CSS definitions in a wordpress blog post because they need to be placed in the header of your blog.

Well, there’s a very simple fix for that, although it’ll require a little bit of modifications to the header.php files of your themes. Enter this code into the header.php file of the theme that you’re using. A safe place to put it is right before the </head> tag.

<?php
  if ($custom_css = get_post_meta($post->ID, 'custom_css', true)) {
    echo '<style type="text/css">' . $custom_css . '</style>';
  }
?>

Once you’ve done this, all you need to do is to create a custom field called ‘custom_css’ on your blog posts and put your custom CSS in there. It ought to look something like this:

The ‘Value’ text entry box is small and somewhat inconvenient to type in, but you still fit an awful lot of CSS in there. For example, for the Rollover Button tutorial I needed to include about a dozen lines of custom css.

One caveat is that it’s unclear exactly what will happen if you have multiple blog posts displayed on the same page and you’ve created conflicting CSS for them. I’d suggest being careful and keep ponential conflicts in mind, or do what I do and operate your blog in one-post-per-page mode.

Comments (1)

  1. Pat Flynn says:

    Your comment “Well, there’s a very simple fix for that, although it’ll require a little bit of modifications to the header.php files of your themes”.
    Could the practicalities of this the modification process be expanded upon so that I could enter the code into the header.php file of the Suffusion theme that I am using?

Leave a Reply

Your email address will not be published. Required fields are marked *