Count all images of a certain post type

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?

Solutions Collecting From Web of "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;
    }
}