When creating a WordPress theme it’s natural to start adding classes and id names to HTML elements as you write them. There is nothing wrong with this. You can use familiar names and be assured that an element has the class that you assigned. There is a downside, in that it doesn’t leverage the plethora of classes already output by WordPress. WordPress produces a long list of classes and ids and can generate dynamic classes and ids that you can’t do by yourself.
The problem, is these classes aren’t visible. At least not until you’ve rendered the page in a browser and looked at the source code. Which is not the way that accustomed to building web pages normally.
post_class() is a function that can generates the following classes:
- .post (or .page or .attachment, depending on the post type)
In a typical post_class will generate the following classes:
- post-# (where # is the id number of this post)
If the post has tags it may generate even more class names. Remember an element may have any number of class names assigned to it.
You could look at the class names as two types: General and Specific. General class names are names that would be the same for every post on the same page. Like post and hentry. Specific classes would be names that might be unique for each post. Things like: post-# (remember the # would be the id number of the post). Some class names will be general and specific. Things like category-name (where name is the name of the category. The category-name might be the same for several posts, while not matching everything on the same page.
Tags, not shown above also generate class names. post_class will generate class names for each tag assigned to a post in the form of tag-name.
What’s important with all of this? Having WordPress generate your class names make your job of creating a template easier and give you more options when creating a template.
Rather than adding your classes to everything, let Wordrpess do it for you. To make use of these classes what’s important is to understand the general classes. These are applied to everything. These might have been the classes you assigned yourself. Instead use the WordPress names and save your self some trouble and standardize your templates and style sheets.
Use post_class by adding to a likely tag within “The Loop”. Remember that post_class generates class names that are specific to posts. That is some of the names will change from post to post. This means that post_class is best used on a unique element that surrounds each individual post.
The post_class method outputs class=”” along with the class names. Use it in this way:
<div <?php post_class() ?>>
... post content ...
Imagine the div above was contained in The Loop. The rest of the post content would be contained within the div above.