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.
Advertisement
Answer
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; }
Let me know if you have any questions! 🙂