wordpress snippets last updated   : April 21, 2014
we now have 630 snippets

Add class to first post in the loop

wordpress snippet

If you wanted to add emphasis to the first post in your blog adding this snippet to the functions.php of your wordpress theme will add the class of “first” to your first post.

snippet :  PHPcopy
add_filter( 'post_class', 'wps_first_post_class' );
function wps_first_post_class( $classes ) {
    global $wp_query;
    if( 0 == $wp_query->current_post )
        $classes[] = 'first';
        return $classes;
}
source →
  • Fabio Simoes

    great! And if I want to add a class always to the fourth column of the loop? For example, I have a loop showing my posts into 4 columns and I need to add this class to the right column. How can I do that?

    Thanks

    • http://wpsnipp.com Kevin Chard

      Hi Fabio, I would need to see your columns loop in order to see what would need to be done.

  • widoz

    Yeah! for adding a last class to the post, need only to add a condition like $wp_query->current_post === $wp_query->found_posts?

    • http://wpsnipp.com Kevin Chard

      Something like this should work,
      if( $wp_query->current_post == $wp_query->post_count-1 )

      • widoz

        Thank you man, i was unsafe about found_posts start from 0 (my bad). However, in same cases post_count isn’t a right choice because it contain the total number of posts being displayed. The use of found_posts or post_count depend which query had been performed, post_count have the same value of “posts_per_page” if is defined in a query or the default value defined into the read settings (sorry for my english).

        • http://wpsnipp.com Kevin Chard

          Hi Widzo, I think it depends on the results you want, if you want to add the class to the last post on every page you would use “post_count” on the very last post only you would use “found_post”

jqsnipp.com | we just launched jquery snippets website