How to count media attachments?

How do I count the number of media attachments a specific post has?

Output example: This post has 22 photos.

Read More

Thanks!

Related posts

Leave a Reply

2 comments

  1. Use this code if you’re in the loop:

    $attachments = get_children( array( 'post_parent' => $post->ID ) );
    $count = count( $attachments );
    

    If you’re not in the loop, substitute $post->ID with the ID of the specific post. But that should count all attachments.

  2. My take would be this:

    $posts = get_posts( array(
                             'post_parent' => $post,
                             'post_type' => 'attachment',
                             'fields' => 'ids',
                         ) );
    
    $count =  count( $posts );
    

    There is no need to query for all post fields if only intent is to count amount.

    Also note that attachment is not necessarily image and that is not easy (possible?) to query for, see wp_attachment_is_image().