2

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

Output example: This post has 22 photos.

Thanks!

2 Answers 2

3

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.

1
  • If in loop arguments can be omitted altogether, function tries to pick parent from global $post in that case automatically.
    – Rarst
    Jun 22, 2011 at 20:47
0

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

3
  • I tried your method but it am only getting the #5, no matter if the post has 21 attachments or three...
    – MTT
    Jun 22, 2011 at 23:03
  • If I remember right there was a core ticket open to add a count attachment hook. Maybe someday.
    – MTT
    Jun 22, 2011 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, 2011 at 8:20

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.