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();

Solutions Collecting From Web of "Query sticky posts with thumbnails"

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,
));

What you are doing is right except that you are careless or you just copied code from somewhere else and pasted in without modifying it.

<?php
$sticky = get_option('sticky_posts');

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

$counter = 1;

$posts = 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 ($posts->have_posts()) :

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

                if ( has_post_thumbnail() ) :
                    echo '<section class="header-sticky-posts'.$counter.'">';
                    echo '<div class="header-sticky-post">';
                            the_post_thumbnail();
                    echo '</div>';
                    echo '</section>';
                    $counter++; 
                endif;

        endwhile;

endif;
wp_reset_postdata();