Add Class to the First Post in the WordPress Loop

Say you want to highlight the first post in the loop in some way. You can add a specific class to it and then style it with CSS. Do this in functions.php:

function wps_first_post_class( $classes ) {
    global $wp_query;
    if( 0 == $wp_query->current_post )
        $classes[] = 'first';
        return $classes;
}
add_filter( 'post_class', 'wps_first_post_class' );

For more on customizing the WordPress loop, see WordPress Template Hierarchy.

Discussion
[  0 Comments  ]

Leave a Comment

To add code, use the buttons below. For instance, click the PHP button to insert PHP code within the shortcode. If you notice any typos, please let us know!