Get images only if parent status is publish

I have a site which uses a custom template page for each image, and users can favorite an image. I am then pulling a page of most favorited images:

$args = array(
'post_type' => 'attachment',
'post_mime_type' => 'image/jpg',
'post_status'=>'inherit', // there for testing
'meta_key' => 'favorites',
'orderby'=>'meta_value_num',
'order'=>'DESC',
'posts_per_page'=>25,
'nopaging' =>true
  );
$query = new WP_Query( $args );

However I only want the images to show there if the parent post status is ‘publish’.

There will be occasions where the status changes temporarily to ‘draft’ then later back to ‘publish’ again – this happens programatically and is done based on author ID to all post which belong to that author.

I could see only two possible ways of doing this:

  1. At the time when the post status of the parent is changed set the post status of attachments which belong to this author to something (Draft? Pending? Something else?) then change it back to inherit at the time I restore the authors posts. However when I tried this, the status of the attachemnt image remained unchanged, so there must be some function in WP that prevents it.

  2. Check each images parent post status before showing them, but this means 25 database calls (yuck) and means I won’t necessarily get 25 images (not a disaster).

  3. Is there a 3?

1 Answer
1

As probably there is not so many unpublished posts with images, You could exclude them from Your WP_Query, adding:

'post_parent' => '-12,-34,-56'

this would add overhead of only one query grabbing id’s of these posts

Leave a Comment