post_class function makes it really easy to write out a variety of class names to post containers that give us a finer-level of control when working on styling WordPress posts.
But there are times in which you may want to actually add a custom class to a post (or to a single post) depending on the nature of the content of the most.
And sure, you can easily add additional parameters to the
post_class function, but those are still static parameters that will be applied to every posts.
What about in cases where you want to add a class if, say, no more tag is present in the content?
Add Post Class in WordPress
First, WordPress provides a filter that allows us to hook into the
post_class function and modify the array of classes that are added to the post.
This can be done easily enough with something like this:
add_filter( ‘post_class’, ‘example_add_post_class_for_more_link’ );
As with most other hooks in WordPress, this will require that we define a function named
example_add_post_class_for_more_link in order to add our custom class.
Now, here’s the the thing:
- The function accepts a single array which includes all of the classes being applied to the post
- Depending on where, in the The Loop, you’re applying this class, you may need to get access to the global
In the following gist, I’ve defined a function will add a
has-no-more-link if the author did not include a
<!–more–> tag in their content:
The code should be easy enough to follow, but for the sake of completeness, here’s what’s going on:
- If the
<!–more–>tag is not found in the post content, then we push the
has-no-more-linkclass to the
This will then give you the ability to style posts that do not have a more tag link within the context of your theme.