update image product

I have a woocommerce with many products, many of these products have no images, or they have images that are no longer available because I have deleted them (error 404).

I would need to create a code in content-single-product.php that if I find an image of the post with an error, I update the images by inserting an external link.

my script is:

$sku=$product->get_sku();
$post_id=$product->get_ID();
$img=$product->get_image();
// apri ricerca amazon
$pagina_ricerca=file_get_contents (“https://www.amazon.com/s?s=date-desc-rank&__mk_es_ES=ÅMÅŽÕÑ&ref=sr_st_date-desc-rank&k=”.$sku);

//estrai url pagina
$estrai_asin=explode(‘ “/amz/”.$filename,
‘post_mime_type’ => $filetype[‘type’],
‘post_title’ => preg_replace( ‘/\.[^.]+$/’, ”, basename( $filename ) ),
‘post_content’ => ”,
‘post_status’ => ‘inherit’
);
$attach_id = wp_insert_attachment( $attachment, $filename, $post_id );
require_once( ABSPATH . ‘wp-admin/includes/image.php’ );
$attach_data = wp_generate_attachment_metadata( $attach_id, $filename );
wp_update_attachment_metadata( $attach_id, $attach_data );
set_post_thumbnail( $post_id, $attach_id );
}
$estrai_img=explode(‘”large”:”‘,$estrai_img_0);
$estrai_img=explode(‘”‘,$estrai_img[2]);
$estrai_img_2=$estrai_img[0];
if ($estrai_img_2){
$filename = $estrai_img_2;
$filetype = wp_check_filetype( basename( $filename ), null );
$wp_upload_dir = wp_upload_dir();
$attachment = array(
‘guid’ => “/amz/”.$filename,
‘post_mime_type’ => $filetype[‘type’],
‘post_title’ => preg_replace( ‘/\.[^.]+$/’, ”, basename( $filename ) ),
‘post_content’ => ”,
‘post_status’ => ‘inherit’
);
$attach_id = wp_insert_attachment( $attachment, $filename, $post_id );
require_once( ABSPATH . ‘wp-admin/includes/image.php’ );
$attach_data = wp_generate_attachment_metadata( $attach_id, $filename );
wp_update_attachment_metadata( $attach_id, $attach_data );
set_post_thumbnail( $post_id, $attach_id );
}

Company
rikilla
Job Type
Project
Location
ASTI
Budget
30
How to Apply
Via email