I am trying to retrieve all of the images associated with a post. I am able to return the ID and to print the ID but when I try to add it with the arguments for get_posts() it returns an empty array. If i don't include a post_parent it gives me all of my images that I have in my media library not all of the images for the post I am looping over. Am I not looping at the right level?
Ive tried manually adding the ID and it still returns an empty array.
$attachments = get_posts( array(
'post_type' => 'attachment',
'posts_per_page' => 1,
'post_parent' => get_the_ID()
) );
var_dump($attachments);
I am expecting a list of the attachments for the post. I want to grab an image from the attachments and print it to the page. But I keep getting empty arrays. Thanks for any help!
The Wordpress Codex says:
Whilst the default WP_Query post_status is 'publish', attachments have a default post_status of 'inherit'. This means no attachments will be returned unless you also explicitly set post_status to 'inherit' or 'any'
So you should try to add 'post_status' => 'inherit'
to your arguments array.
Simplyuse the wordpress core function get_attached_media() to get the attachments of your post.
get_attached_media( string $type, int|WP_Post $post )
Retrieves media attached to the passed post.
Simply pass an empty string as $type to bypass the mimetype filter.