WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I followed two posts related to my query. One was about the number of images attached to a post and second about showing all images of a certain post type. I tried to combine the two codes in the following way but it didn't help:

$query = new WP_Query( array( 'post_type' => 'gallery', 'posts_per_page' => -1 ) );
if( $query->have_posts() ){
        $attachments = get_children( array( 'post_parent' => $parent->ID, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => 'ASC', 'orderby' => 'menu_order ID' ) );
        $count = count( $attachments );

Can anyone help me in counting all images attached to a certain post type?

share|improve this question
What have you done so far? Please post some code. – hakre Jan 2 '12 at 21:52
Updated the question. – navjotjsingh Jan 3 '12 at 4:17
you need to declare $count outside of your while loop and then within the loop add each iteration to it, like $count += count( $attachments ); to end up with the total. – Milo Jan 3 '12 at 4:45
That doesn't work. It inflates the count to much more than the total number of images in the Media library. I just want the number of images attached to the all the posts of type 'gallery'. – navjotjsingh Jan 3 '12 at 5:09
up vote 2 down vote accepted

Try putting this in your functions file, and then place <?php $attachment_count; ?> in a template file.

function attachment_count() {
global $post;
    //Get all attachments
    $attachments = get_posts( array(
        'post_type' => 'attachment',
        'posts_per_page' => -1
    ) );

    $att_count = 0;
    if ( $attachments ) {
        foreach ( $attachments as $attachment ) {
            // Check for the post type based on individual attachment's parent
            if ( 'gallery' == get_post_type($attachment->post_parent) ) {
                $att_count = $att_count + 1;
        echo $att_count;
share|improve this answer
Thanks a lot. This works. – navjotjsingh Jan 6 '12 at 6:57

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.