skip to Main Content

I want to style the first post differently so I am trying to use a simple counter that will add a class to the first post.

First, on index.php I have this

if ( have_posts() ) :
    $postCount = 0;
    while ( have_posts() ) :
        the_post();
        $postCount++;
        get_template_part( 'template-parts/content', get_post_type() );
    endwhile;
endif;

and then on content.php I have

<div class="article-wrapper <?php echo $postCount; ?>"> 

but $postcount is always 1

If I move $postCount = 0; and $postCount++; to content.php the value never changes either.

I can create a custom Blog page template but I would like to see this working.

2

Answers


  1. You would have to apply a filter post_class. The below code came from this article: https://www.isitwp.com/add-class-to-first-post-in-the-loop/

    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;
    }
    
    Login or Signup to reply.
  2. sorry for late answer but I think it will help you in other way.
    in your index.php you can change your code to this

    if ( have_posts() ) :
        $postCount = 0;
        while ( have_posts() ) :
            the_post();
            $postCount++;
            get_template_part( 'template-parts/content', get_post_type(),['post_counter'=>$postCount] );
        endwhile;
    endif;
    

    and in your content.php

    if ( $args['post_counter'] ) {
          echo $args['post_counter'];
        }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search