I am working, on a code, where i need to loop Through all posts of a given author, and then for each post of that author, count the number of media attachments, the post has and then echo it.

I am able to loop Through posts, and it works as expected, but then i want to count the number of attachments of each post, where i fail, please help.

$author_posts = get_posts( array('author' => $author_id, 'numberposts' => -1, 'post_type'=> array('post','download', 'attachment' ), 'post_status'=> array('publish','privatised'), )); 

This was the orignal loop.

Below is the code, here the words are counted as expected, comments are counted as expected too. For simplicity in prefered not to include the echo portion

 foreach ( $author_posts as $post ) {   
$View_Count = absint( get_post_meta( $post->ID, 'Creation_Views', true ) ); 
$Word_Count = str_word_count( strip_tags( get_post_field( 'post_content', $post->ID )));
$Image_Count = count( get_attached_media( 'image', $post->ID ) );
$Comment_Count = get_comments_number($post->ID) ;

Please help, the $Image_Count, always gives 0, regardless of which post i check. I have over 500 posts, and it shows 0 for all of them, while all of them atleast have 1 attachment

2 Answers 2


If you are counting post images, try the following. It doesn't capture a post's featured image, but it does get images in the post content.

$attached_images = get_children( "post_parent=$post->ID&post_type=attachment&post_mime_type=image;
  • Well honestly, i wanted every attachment uploaded to a post, regardless of whether it has been inserted in content or not. This could include featured imgs, vids etc... But still i can manage with it. So thank you Feb 16, 2020 at 5:17
  • I haven't tested, but, possibly, you could leave off the part of the query that is: '&post_mime_type=image' and get all attachment types. Separately, this page: codex.wordpress.org/Function_Reference/get_post_mime_type discusses the different mime types that could be queried. Feb 16, 2020 at 23:27

Must be used inside the loop

$post_images = get_children( $post->ID );
$images_count = count( $post_images );
echo $images_count; 

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.