How To Add A Class To Post Div For Specific Posts Using post_class
In WordPress, there are many scenarios where we might want to add a unique class to a post’s container div. It can be easier to control the layout of a Post using css rather than creating multiple template pages. By adding a unique class, we can show/hide certain Post elements, change positioning of divs, apply different styling to text, etc.
To add our custom class “my-custom-class” as well as all the available post styles (id, categories, post type, etc), we would add the following to our Post div in the single.php template file:
echo '<div class="' . join( ' ', get_post_class("my-custom-class") ) . '"><h1><a href="' . get_permalink() . '">' . get_the_title() . '</a></h1>';
Now we can target our css based on the new classes we’ve applied.
If we just want to keep it simple by only using our custom class (without all the extras such as id, categories, post type, etc) , we would just define it directly.
echo '<div class="my-custom-class"><h1><a href="' . get_permalink() . '">' . get_the_title() . '</a></h1>';
We could also add this class conditionally. We might only want to include the class if a Custom Field have a value (or specific value), or for custom Post Type, or for a specific Category.
In this example, we apply the class if our Custom Field has a value
if(!empty( get_post_meta(get_the_id(), 'custom-field-name', true) )) { echo '<div class="' . join( ' ', get_post_class("my-custom-class") ) . '"><h1><a href="' . get_permalink() . '">' . get_the_title() . '</a></h1>'; }