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.

I'm trying to figure out how to count and display the number of images in a gallery with WP 3.5. I was following an old post on Ottopress, querying the DB for attachments but it seems the galleries are now contained in shortcodes.

Is it possible to extract the shortcode from the post and count the IDs? What is the best way to accomplish this?

share|improve this question
Where do you need the number? –  toscho Jan 11 '13 at 20:47
In the loop, similar to how ma.tt displays gallery posts. –  javy Jan 12 '13 at 8:52

3 Answers 3

This works:

$images = get_children( array(
    'post_parent' => $post->ID,
    'post_type' => 'attachment',
    'post_mime_type' => 'image',
    'orderby' => 'menu_order',
    'order' => 'ASC',
    'numberposts' => 999
if ( $images ) {
    $total_images = count( $images );

The variable $total_images will hold the count of images in your gallery.

share|improve this answer
Not getting any results for this. In wp_posts in the DB, the only posts which are attachments that I'm seeing are Featured Images. –  javy Jan 22 '13 at 20:50
Are the images actually attached to the post, or are you just referencing them directly from the media library? The code works perfectly for me in all the themes I've used it in. –  justmattb Jan 23 '13 at 6:09
I'm using the native WP 3.5 gallery shortcode. It doesn't attach them to posts, it references the media IDs directly. –  javy Jan 23 '13 at 15:59

This worked well for me for a gallery post format... where is was safe to assume only all attachments were in 1 gallery. Doesn't seem totally relevant but thought I'd throw it out there.

$num_attachments = array_sum ( (array) wp_count_attachments('image') );
share|improve this answer

If you need count after gallery itself was processed, the light way might be to hook into post_gallery filter in gallery_shortcode() and note down explicitly included posts from arguments it passes.

It does get somewhat complicated with multiple galleries in same post, but it's hard to recommend specific approach without full context of your needs.

share|improve this answer

Your Answer


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.