How do I count the number of media attachments a specific post has?
Output example: This post has 22 photos.
Thanks!
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It only takes a minute to sign up.
Sign up to join this communityUse 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.
$post
in that case automatically.
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()
.
$post
should probably have been $id
in example). Also try var_dump($posts)
to make sure you are getting sane results.