Like the blog? Get the book »

Add Classes to post_class

Add Classes to post_class

The post_class() function in WordPress is pretty darn useful. It is used like this, in most templates, in a wrapping div of all the content you are outputting:

<div <?php post_class() ?> id="post-<?php the_ID(); ?>">
   <!-- Post stuff -->

I was in a circumstance where I wanted to add an additional class to what that was outputting. My thought process went like this:

  1. Arg. I guess I’m going to have to write a function to filter the output of that function. Let’s begin the research.
  2. Wait. I bet that function has an alternate that returns a string rather than echoes it. I’ll just use that, and echo it out along with my custom class.
  3. Double wait. I bet those smart WordPress folks have thought of this…

1. Filtering

This kind of thing is generally beyond my comfort zone, but you’d basically write your own little function which takes in what the output would have been, add you own stuff to it, then return the new value.

Then call the new function with a filter in your functions.php file:


2. Output exiting classes, then add yours

Like most functions that echo stuff, there is a version that doesn’t echo stuff, in which “get_” prefaces the function name. I didn’t even have to look it up I just knew there would be. Since it’s a list, this function returns an array, so to output them, you’ll need to loop through the array:

<div class="<?php $allClasses = get_post_class(); foreach ($allClasses as $class) { echo $class . " "; } ?> group" id="post-<?php the_ID(); ?>">

The cool part here is that is doesn’t add “class=” in the output, you can do that yourself, meaning that I can add my own classes after the output is finished.

3. Built in…

Of course, as it turns out, this is far easier than #2 made it out to be. To add additional classes, just pass them as a parameter!

<?php post_class('special'); ?>

2 responses

  1. Certainly does look useful. I really should try this out next time I build a theme. :)

  2. I didn’t about the built-in method. But the filtering is darn easy. Define the function and pass it an array. Add items to this array and return it.

    function additional_classes($c) { $c[] = 'myclass'; return $c; }
    add_filter('post_class', 'additional_classes');

    Thanks for the tip, Chris.

Comments are closed for this post. Contact us with any critical information.
© 2009–2024 Digging Into WordPress Powered by WordPress Monzilla Media shapeSpace