Your solution seems overly complicated to me. WP_Query
can do nearly all of the work, you just need to construct a meta_query
to look for thumbnails. The code is slightly truncated but here is the idea:
$categories = array(1,2,3); // your specific category IDs
$first_thumb = new WP_Query(
array(
'posts_per_page' => count($categories),
'category__in' => $categories,
'meta_query' => array(
array(
'meta_key' => '_thumbnail_id',
'compare' => 'EXISTS'
)
),
)
);
if ($first_thumb->have_posts()) {
while ($first_thumb->have_posts()) {
$first_thumb->the_post();
the_post_thumbnail();
}
}