Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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

Output example: This post has 22 photos.

Thanks!

share|improve this question

2 Answers 2

up vote 3 down vote accepted

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.

share|improve this answer
    
Thanks @EAMann! –  mattrepublic Jun 22 '11 at 20:38
    
If in loop arguments can be omitted altogether, function tries to pick parent from global $post in that case automatically. –  Rarst Jun 22 '11 at 20:47

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().

share|improve this answer
    
I tried your method but it am only getting the #5, no matter if the post has 21 attachments or three... –  mattrepublic Jun 22 '11 at 23:03
    
If I remember right there was a core ticket open to add a count attachment hook. Maybe someday. –  mattrepublic Jun 22 '11 at 23:04
    
@M.Taylor worked for me in quick test... make sure you are passing ID and such ($post should probably have been $id in example). Also try var_dump($posts) to make sure you are getting sane results. –  Rarst Jun 23 '11 at 8:20

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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