Add Class To The First Post in The Loop

Home » Blog » WordPress Development » Add Class To The First Post in The Loop

Your theme displays blog post lists using a template that is called The Loop. If you want to add a custom CSS class to the first post in this loop, you can do so easily by adding a filter function for the post_class filter.

To do this, add the following code to your functions.php file or a custom plugin:

function add_custom_class_to_first_post( $classes ) {
    global $wp_query; // Get the current query being run.

    // Check if this post in the current loop is the first post. The list starts from 0.
    if( $wp_query->current_post === 0 )
        $classes[] = 'first-post-custom-class';

    return $classes;
}
add_filter( 'post_class', 'add_custom_class_to_first_post' );

The above code adds a custom filter function called add_custom_class_to_first_post to the post_class filter. The post_class filter lets you filter the classes that will be added to a post. In the above code, we add a custom class called first-post-custom-class to the classes array if this is the first post in the loop. Replace first-post-custom-class with whatever class name you want to use.

Leave a Reply

Your email address will not be published. Required fields are marked *

Register an account to save your snippets or go Pro to get more features.