Add style class to first post in the WordPress loop
WordPress can be used to easily create a website with your desired layout and design. Quite often, you find a website where the first entry in the list of articles is differently styled than the rest. How can you make the first post in the WordPress query loop look distinct from the others? You need to add a CSS style specific to the first article in the post list and then style it accordingly. Now the real problem—how do you add a CSS style class only to the first post in the WordPress loop?
If you wanted to emphasise the first post in your blog, copy-paste the following snippet to the functions.php file of your wordpress theme. It will add the class “first” to the first post in the query loop. You can replace the word with your own class name or add more classes by adding a comma-separated array list as the value of $classes[] array within the quotes.
add_filter( 'post_class', 'sww_post_class' ); function sww_post_class( $classes ) { global $wp_query; if( 0 == $wp_query->current_post ) $classes[] = 'first'; return $classes; }
What if you want to style the first few posts differently? Let us say you want the first four posts to be distinct. You can easily extend the code by adding more conditions to add different classes to second, third, fourth posts and so on.
add_filter( 'post_class', 'sww_post_class' ); function sww_post_class( $classes ) { global $wp_query; if( 0 == $wp_query->current_post ) // If FIRST post { $classes[] = 'first'; return $classes; } elseif( 1 == $wp_query->current_post ) // If SECOND post { $classes[] = 'second'; return $classes; } elseif( 2 == $wp_query->current_post ) // If THIRD post { $classes[] = 'third'; return $classes; } elseif( 3 == $wp_query->current_post ) // If FOURTH post { $classes[] = 'fourth'; return $classes; } }