get post attachments of a particular size

Is there a good way to know if a post has an image attachment of a particular size? I’m trying to fetch 5 random posts, but I only want results that have image attachments with a (custom) size of “extra_large”.

I’m trying:

Read More
$images = get_posts( array(
  'post_type' => 'attachment',
  'orderby' => 'rand',
  'posts_per_page' => -1,
) );
foreach ($images as $img) :
  $image = wp_get_attachment_image_src( $img->ID, 'extra_large' );
  if ( !empty($image) )
    $carousel[] = array($img->post_parent, $image);
endforeach;

…but I don’t particularly like this as I have to grab every single image, and then loop through them to see if there’s an extra_large version. I’m just using the first 5 items in $carousel[], but as my data set is very large there’s a lot of un-needed processing. Also, I then have to do another call to get the parent from the ID.

Is there a more elegant way to do this?

Related posts

Leave a Reply

1 comment

  1. The image attachment type is stored in the postmeta table in the _wp_attachment_metadata meta key. The data is serialized, so it can’t be filtered on. But you could use a meta_query in your query:

    $images = get_posts( array(
      'post_type' => 'attachment',
      'orderby' => 'rand',
      'posts_per_page' => -1,
      'meta_query' => array(
            array(
                'key' => '_wp_attachment_metadata',
                'value' => 'extra_large',
                'compare' => 'LIKE'
            )
        )
    ) );
    
    foreach ($images as $img) :
      $image = wp_get_attachment_image_src( $img->ID, 'extra_large' );
      if ( !empty($image) )
        $carousel[] = array($img->post_parent, $image);
    endforeach;
    

    That would be much more efficient — because it should only retrieve the attachments that have the ‘extra_large’ version.

    Alternative Option:
    Attach the images to a post, and then just use post_parent in your query, as is shown in the answer of this question: Get all image from single page