Thord Daniel Hedengren - Smashing WordPress_ Beyond the Blog-Wiley (2014)

(avery) #1

136 PART II • Designing and Developing WordPress Themes


Most of the time, however, you don’t want to style individual posts per se, but rather posts
belonging to a certain category. You can check for this using a conditional tag and a short PHP
snippet, of course, but post_class() already has you covered. This template tag returns a line
of classes for you to style any way you want, depending on where the post belongs and so on.

First, you’ll get the post ID as a class as well, so your post with id="post-674" will also
have the class post-674. You’ll also get every category that the post belongs to, with
category- in front of the category slug. So a category called Website News, which usually
gets the slug website-news, would return the class category-website-news from
post_class(). The same goes for tags; if you tag something with funny, you’ll get that
returned as the class tag-funny.

You’ll also get the classes post and hentry, the former making sure that post_class() is
compatible with older WordPress themes, which usually describe the article containers for
posts with the post class, and the latter telling us the article belongs to an entry. In fact,
that usage is still there, too.

So what good does this do? First, you can change the category styling, which is probably the
most common usage for these classes. Say you’ve got a news category called News, with the
slug news; hence, you’d get class="category-news" from post_class() whenever it
was used. And say you want the links in this category to be green, and why not put a green
border line to the left side as well, to really make it obvious? This can be easily achieved:

.category-news {
padding-left: 20px;
border: 5px solid green;
border-width: 0 0 0 5px;
}

.category-news a { color: green; }

Now every post belonging to the News category would get green links and a green border line
to the left. This is great because categories can be used to control design elements, and tags in
turn should be used to further sort the posts. For example, I might have a tag for My Fave, a
feature I’m running. Every post that is one of my faves will get a My Fave graphic in the top
right — not clickable or anything, just a marker so that people know it is one of my favorites:

.tag-my-fave { background: url(myfave.gif) top right no-repeat; }

This would output a background image, myfave.gif, in the top-right corner (and not repeat it)
every time post_class() returns the tag with the slug my-fave. Naturally, it is no lucky
coincidence that that is the actual slug for my My Fave tag, now is it?

Finally, you can pass a specific class to post_class(), which may be useful at times. Maybe
you want to add the class stars to single posts? If so, just edit your post_class() code in
the single.php template to this:

<article id="post-<?php the_ID(); ?>" <?php post_class( 'stars' ); ?>>
Free download pdf