Add a different class name to each sticky post?

I am trying to set up a featured content section of my blog. This will contain two sticky posts.

I have a custom loop which will only display the two sticky posts, in the loop I then get a content-featured.php template which has the structure of the sticky posts.

In the main post div I use post_class(). I know I can pass a value like post_class('featured') but I would like to have a different class name for each sticky post, i.e. featured-0, featured-1.

I have attempted to create a function in functions.php, but as I know very little about PHP, I am struggling to get it to work. Here’s what I have:

//add classes to sticky posts
function gwad_sticky_classes( $classes, $class ) {
    $sticky = get_option( 'sticky_posts' );
    if ( $sticky ) {
        $query = new WP_Query( $sticky );

        $sticky[0] ='featured-0';
        $sticky[1] = 'featured-1';

    }

    return $classes;
}
add_filter( 'post_class', 'gwad_sticky_classes', 10, 2 );

As you can see, I don’t have a clue what I’m doing, any help would be greatly appreciated.

2 Answers
2

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