Add Class to post_class() to a WordPress Theme Template
There comes a time in every web dev’s blogging life that standard themes just won’t cut it. At that point the only thing to do is to code one up yourself or modify an existing theme. That might be as easy as copying a piece of code from one place to another or simply removing an element entirely. Other more advanced changes would be things like creating new loops for other pieces of content and that’s where I stumbled into the problem of: How do I add another Class to post_class()?
Reasons You’d Want to add a new Class to post_class()
Recently when I began creating a new homepage template for one of my other sites I ran into a little problem. I had a nice little code snippet of a standard WordPress loop I’d written ages ago that I popped into a new ‘latest posts’ section on the new homepage and it pulled the featured image and the title, omitting actual post content, just as I had wanted.
I then moved onto styling the entries with CSS, so I opened up firebug and got everything aligned properly. It looked good but I wanted it polished a bit more so I thought about wrapping each entry in it’s own div and styling it with a homepage specific class but it already used a clever little function called
That single line of code can be found at the opening of almost every single piece of post or page content in WordPress themes. The reason it is included is because it adds the default classes to every post/page/ about the format/category/tag allowing you to style every matching post the same. Be it individual styles for different post_formats – or even depending on categories, tags or other taxonomies – classes are added accordingly for you by WordPress.
How to Add Classes to post_class()
I needed to add another class to the list that post_class() creates. To do so I could have echo’d out the list of classes provided by
class=' but there’s an even better way of doing it that is so easy it’s unbelievable.
Adding a Class to post_class()
You need only pass the new class name to the function call like so. I called my class home-latest-list but you could name yours anything you want.
You see adding classes to post_class() is so easy that there’s no reason for you not to experiment and see what you can do with your existing theme that makes it unique to your site and your brand.
Notice: WP_Query was called with an argument that is deprecated since version 3.1.0!
caller_get_postsis deprecated. Use
ignore_sticky_postsinstead. in /var/www/html/wp-includes/functions.php on line 4080