1

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() ){
    while($query->have_posts()){
        $query->the_post();
        $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?

4
  • What have you done so far? Please post some code.
    – hakre
    Jan 2, 2012 at 21:52
  • Updated the question. Jan 3, 2012 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, 2012 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'. Jan 3, 2012 at 5:09

1 Answer 1

2

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;
    }
}
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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