Add a Post Class in WordPress: The More Tag

WordPress’ 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 $post variable

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-link class to the $classes array.

This will then give you the ability to style posts that do not have a more tag link within the context of your theme.

2 Comments

This is any interesting little quirk, I’m going to have to see if I can put it to use somewhere … just because I like the idea of it :)

Trackbacks and Pingbacks

WordPress: More Tag Wrapper - Tom McFarlinDecember 2, 2013 at 10:07 am

[…] as there are times where we may want to indicate that a class has (or doesn’t have) a more tag, we may also want to wrap the tag in a row with columns on either side of the […]

Leave a Reply

Name and email address are required. Your email address will not be published.

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>