Count all images of a certain post type

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

Leave a Comment