How to add a counter to your post_class in WordPress

For the redesign of this site, I wanted to implement various design elements, in particular related to the Responsive Design, made possible by iThemes Builder.

One of those elements is that when visiting the home (blog index) page in mobile view, only the excerpt on the first post is displayed, all other posts are displayed as titles only. Of course, I could have edited the theme file to add a counter, and conditional code to display or not display the excerpt. However, I try to minimise changes to template files, and prefer to use a function, and CSS to accomplish such functionality.

I came up with the following solution.

First of all, the function to add a counter. This code should be added to your active themes’ functions.php in <php> tags:

function get_post_counter($classes) {

    $post_counter = $GLOBALS['wp_query']-&amp;gt;current_post + 1;

    $classes[] .= &amp;quot;postcount-&amp;quot; . $post_counter;
    return $classes;
add_filter('post_class', 'get_post_counter');

The function will hook into the post_class filter, and add the string postcount-n (where n is a sequential number, starting with 1 for the first post, 2 for the next etc.) to the post classes in which all posts are wrapped. In case of pagination, so on page 2 of the blog index page, the counter will be reset to 1.

Next thing to do is to add the appropriate css code to either hide or display the excerpt.

Builder uses two, and optionally three stylesheets to facilitate its responsive design. style-mobile.css will be used if the viewport is below a certain with, and optionally, one can add style-tablet.css to add specific styling for devices that are generally larger than a mobile phone display, and smaller than a desktop monitor.

so I added the following code to the style-mobile.css stylesheet, so that it will only apply if the viewport is less than a predefined value (which is when the style-mobile.css “kicks in”).

.builder-view-home .entry-content {
    display: none;

.builder-view-home .postcount-1 .entry-content {
    display: block;

It will hide all the post content on the homepage first, and then, however it will unhide such content on the post content with post-class .postcount-1.

And there we have it, when you resize the browser, or view the blog index page on a mobile device, only the first posts’ excerpt will be displayed.


  1. Sridhar Katakam

    Thanks for writing this.

    Just to make the CSS a little bit shorter, can we not replace “.builder-view-home” with “.home”?

Leave a Reply