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

Output example: This post has 22 photos.



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.

| improve this answer | |
  • 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().

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

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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