Add a different class name to each sticky post?

Here’s a solution that adds additional sticky classes, one for the post ID and one for the sticky post counter.

/**
 * Adds .featured-{$post_id} and .featured-{$sticky_counter}
 * class names to sticky posts.
 *
 * @param array $classes An array of post classes.
 * @param array $class   An array of additional classes added to the post.
 * @param int   $post_id The post ID.
 *
 * @return array
 */
add_filter( 'post_class', 'gwad_sticky_classes', 10, 3 ); 
function gwad_sticky_classes( $classes, $class, $post_id ) {

    // Bail if this is not a sticky post.
    if ( ! is_sticky() ) {
        return $classes;
    }

    // Counter for sticky posts.
    static $gwad_sticky_counter = 0;

    $classes[] = 'featured-' . $post_id;
    $classes[] = 'featured-' . ++$gwad_sticky_counter; 

    return $classes;
}

Edit: Here’s an alternate version that avoids using the static variable:

add_filter( 'post_class', 'gwad_sticky_classes', 10, 3 ); 
function gwad_sticky_classes( $classes, $class, $post_id ) {

    // Bail if this is not a sticky post.
    if ( ! is_sticky() ) {
        return $classes;
    }

    global $wp_query;
    $classes[] = 'featured-' . $post_id;
    $classes[] = 'featured-' . ( string ) ( $wp_query->current_post + 1 );

    return $classes;
}

Leave a Comment