Get only posts with featured images

Nearly in every project that I work on I need to make a query on posts that have a feature image. I usually start digging into Codex and start wondering which is better.

Well according to codex I’d better use wp_query instead of get_posts and for my purpose, this seems the way to go:

$args = array(
   'post_type' => 'product',
   'orderby' => 'desc',
   'meta_key' => '_thumbnail_id'
);

And perhaps a classier solution:

  $args = array(
    'post_type' => 'product',
    'orderby' => 'desc',
    'meta_query' => array(
        array(
            'key'     => '_thumbnail_id',
            'compare' => 'EXISTS'
        )
    )
  );

Leave a Reply

Your email address will not be published. Required fields are marked *