As I’ve continued to work on the theme that I’m planning to use after Standard (and that I’ hoping to begin dogfooding within the next month or so), there have been a couple of features that I’ve wanted to implement for the sake of styling.
For example, there are times where I want to be able to style a single post, and though there are a number of ways one can go about doing this, I like to try to be consistent in how I approach the solutions I implement.
To that end, I’ve wanted to add a custom class name to a single post but only only the single post page.
Add a Class to a Single Post
If you’ve ever done any type of theme development, then you’re likely familiar with the
post_class function and its implementation.
If not, it’s simple enough:
<div class=”<?php post_class(); ?>”></div>
And then adding custom classes can be done like this:
<div class=”<?php post_class( ‘my-custom-class’ ); ?>”></div>
This will, in turn, generate a
div element that has a variety of class names each of which are added by WordPress and that also include the class you’ve passed as an argument – specifically, “my-custom-class.”
I’ve mixed feelings about following this approach:
- If defining custom classes, you’re doing so in the templates, and you’re adding a variety of class names that are not consistent for each post, then it’s going to make it difficult to maintain over time.
- This makes it possible to write what I consider to be business logic in the template file – which should essentially be view logic – such that you could technically write something like
<div class=”<?php post_class( is_single() ); ?>”></div>
And just because it can be done doesn’t mean that it should be done.
Instead, if you need to incorporate more advanced techniques when adding class names to posts in WordPress, you can define a function to do so by hooking into the
Case in point, check out this gist.
It should be easy enough to understand:
- When the post class action is fired, this function will execute.
- It receives an array of class names (identified by
- If the current post is a single post, then it will add the ‘single-post’ class name to the array; otherwise, it will do nothing.
- The array of classes will be returned to WordPress for it to render to the browser
Obviously, this is a simple example; however, doing this in a function rather than in the template keeps the logic cleanly separated.
It also makes it possible to introduce more complex logic into the functions file for adding classes to posts rather than cluttering up the templates with unnecessary code.
As long as you’re calling
post_class() in your templates and you’re properly hooking your own function up to the action, you should be good to go.