I am trying to retrieve attachments that are attached to my current post. This is the code that I am trying to use. What I’m attempting to do is query all of my posts that are of custom post type business-manager. From within that loop I am starting another query to retrieve the attachments associated with that post. If I var dump the $attachment variable I get an empty array. If I pass the array for attachment variable into get_posts($args) then do a var dump I can retrieve all of the images. How can I do this using a new WP_Query object?
$my_query = new WP_Query( array(
'post_type' => 'business-manager',
'posts_per_page' => 1,
'tax_query' => array(
'taxonomy' => 'business-type',
'field' => 'slug',
'terms' => 'featured'
)
) );
$attachment = new WP_Query( array(
'post_type' => 'attachment',
'numberposts' => -1,
'post_status' => null,
'post_parent' => $my_query->post->ID
) );
From get_media_items function and his code, you can use get_children adding mime type for images:
That will get you an array ($images) of images attached to $post_id. In you case, if you’re inside a loop, $post_id should be equal to $post->ID
Not exactly a WP_Query implementation as you asked for, but it’s easy.
If you still need the WP_Query way, you can use your own code i think (not tested). Inside a loop:
$attachment = new WP_Query( array(
'post_parent' => $post->ID
'post_type' => 'attachment',
'posts_per_page' => -1,
'post_mime_type' => 'image'
) );