KISS Me, WordPress! Easy Category List for Stylesheet and ID for Pages

Keep IT Simple, Stupid.

In my way of making things harder than necessary I stumbled upon something simple. At times nothing seems simple with CSS! Check it out.

Trying to style a particular post, based on whether it was a password-protected post or not, I found that using the category assigned could help – on the condition that one category name was reserved for the password-protected posts. Look at this piece of WordPress code:

<?php foreach((get_the_category()) as $cat)
echo $cat->category_nicename;

Basically, what we are asking for here is to create an array that holds the names of the categories, and then return the nice names of each category in lowercase and with multiple words separated by hypens.

So, being able to assign category names on the fly gives us the ability to assign classes based on the category. Use the above PHP code snippet in the index.php, category.php and single.php files of your WP theme.

Remembering that we can assign more than one class to an xhtml feature, on line 5 or 6 in each of the 3 files replace

<div class="post"


<div id="post" class="post cat-<?php foreach((get_the_category()) as $cat)
echo $cat->category_nicename;

Now, in your stylesheet you can target classes like cat-owls, cat-hawks and cat-bald-eagles on your site about big birds.

The KISS part comes in where I was going through steps to create a page template to replace a Page that was already written so that I could style it differently than the rest of the blog. What? Instead of going through all that, all I needed to do was pick up the ID number of the “post” of that page. Duh!

How simple of me to forget that the pages, as well as the posts, that we write in WordPress are assigned ID numbers. Just use the #page-ID in your stylesheet! Oh yeah, pick up the ID numbers of posts and pages in the admin area under Manage/ Posts or Pages.

Comment, comment, comment…but which comment code goes where?

Commented code is worth its weight in gold when it comes time to decipher it. Unfortunately, the codes for commenting in xhtml, css and php are not all the same. So, for reference sake here are the comment codes you’ll need and where to use them.

Where xxx is your comment, for

  • xhtml (html) and php (outside php code) use <!-- xxx -->
  • css use /* xxx */
  • php (inside php code or between <?php and ?>) use // xxx
  • multi-line comments inside php use /* xxx */

Comments are very helpful in troubleshooting style changes. When creating your designs take a few seconds to jot down a comment here and there.

Great uses of comments include labeling the starting and ending location of id- or class-identified divs, putting temporary holds on features that may or may not be needed in the final design — often called commenting out code, sectioning long stylesheets into more easily readable forms, and specifying the author or location of the code.