How to Loop Through Posts and Count Attachments using Get Media Attachments

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

Read more here:: How to Loop Through Posts and Count Attachments using Get Media Attachments

Leave a Reply

Your email address will not be published. Required fields are marked *