How do i replace the title attribute of img tag with the image caption

// Replace the title of img tag with image caption

function wpdocs_filter_gallery_img_atts( $atts, $attachment ) {
    $attachment = get_post( $attachment->ID );
    if ( $caption = $attachment->post_excerpt) {        
            $atts['title'] = $caption;        
    }
    return $atts;
}
add_filter( 'wp_get_attachment_image_attributes', 'wpdocs_filter_gallery_img_atts', 10, 2 )

This function is working for me local host but some how not working on the live site