Query sticky posts with thumbnails

I need to display max 5 latest sticky posts that have a thumbnail. And I need to have accurate counting of the displayed posts. I’ve tried to exclude sticky posts without a thumbnail with meta_query, but with no luck.

$sticky = get_option('sticky_posts');

if (empty($sticky)) {
    return;
}

$counter = 1;

$r = new WP_Query(array(
    'posts_per_page' => 5,
    'post__in'       =>  $sticky,
    'meta_query' => array(
        array(
            'key'     => '_thumbnail_id',
            'compare' => 'EXISTS',
        ),
    ),
    'post_status'    => 'publish',
    'orderby'        => 'post__in',
    'post_type'      => array( 'post' ),
));


if ($r->have_posts()) :

    echo '<section class="header-sticky-posts '.$post_count.'">';

        while ( $r->have_posts() ) : $r->the_post();

            echo '<div class="header-sticky-post">';
                // Post content
            echo '</div>';

        $counter++; 
        endwhile;

    echo '</section>';

endif;
wp_reset_postdata();

2 Answers
2

You need to set ignore_sticky_posts to true in your query arguments. This way you exclude sticky posts and only focus on the post ID’s array being passed to post_in

'ignore_sticky_posts' => true,

EDIT

If this does not make much sense, please see my answer here to similar question where I have explained it a bit better. Be sure to check it out

THE CODE

$r = new WP_Query(array(
    'posts_per_page' => 5,
    'post__in'       =>  $sticky,
    'meta_query' => array(
        array(
            'key'     => '_thumbnail_id',
            'compare' => 'EXISTS',
        ),
    ),
    'post_status'    => 'publish',
    'orderby'        => 'post__in',
    'post_type'      => array( 'post' ),
    'ignore_sticky_posts' => true,
));

Leave a Comment