WP Query attachments used as thumbnail

337 Views Asked by At

Here's my kind-of unique and interesting situation:

I want to query all wordpress attachments (images) that have been used before as thumbnail images. The end result will be this:

enter image description here

as you can see, I want to mark the pictures that have been used as thumbnail in other posts, so that I don't use them again.

Currently, even though most images have been used as thumbnails, none of them appears as attached:

enter image description here

So it seems only when I upload an image from post editor it appears as "attached" but it doesn't count as "attached" when a thumbnail/featured image is selected from the library.

I'm using this query to get all images that are used as thumbnails but it doesn't seem to work at all. It returns all the images regardless:

$args = array(
  'posts_per_page' => -1,
  'post_status' => 'inherit',
  'post_type'=> 'attachment',
  'post_mime_type' => array(
    'image/jpeg',
    'image/gif',
    'image/jpg',
    'image/png'
  ),
  'meta_query' => array(
    array(
      'key' => '_thumbnail_id',
      'value' => '?',
      'compare' => 'EXISTS'
    )
  )
);
$used_thumbnails = new WP_Query($args);

Am I doing something wrong? I've spent many hours and can't seem to figure out.

1

There are 1 best solutions below

0
On

Since WordPress saves the attachment status only in the meta of the post and not in the meta of the attachment, you will have to do a custom query without WP_Query. It's relatively simple.

global $wpdb;
$query = "SELECT meta_value FROM {$wpdb->prefix}postmeta WHERE meta_key = '_thumbnail_id'";
$results = $wpdb->get_results($query, ARRAY_A);
var_dump($results);