woocommerce update product featured image from uploads url

Solutions on MaxInterview for woocommerce update product featured image from uploads url by the best coders in the world

showing results for - "woocommerce update product featured image from uploads url"
Vincenzo
27 Aug 2020
1function Generate_Featured_Image( $image_url, $post_id  ){
2    $upload_dir = wp_upload_dir();
3    $image_data = file_get_contents($image_url);
4    $filename = basename($image_url);
5    if(wp_mkdir_p($upload_dir['path']))
6      $file = $upload_dir['path'] . '/' . $filename;
7    else
8      $file = $upload_dir['basedir'] . '/' . $filename;
9    file_put_contents($file, $image_data);
10
11    $wp_filetype = wp_check_filetype($filename, null );
12    $attachment = array(
13        'post_mime_type' => $wp_filetype['type'],
14        'post_title' => sanitize_file_name($filename),
15        'post_content' => '',
16        'post_status' => 'inherit'
17    );
18    $attach_id = wp_insert_attachment( $attachment, $file, $post_id );
19    require_once(ABSPATH . 'wp-admin/includes/image.php');
20    $attach_data = wp_generate_attachment_metadata( $attach_id, $file );
21    $res1= wp_update_attachment_metadata( $attach_id, $attach_data );
22    $res2= set_post_thumbnail( $post_id, $attach_id );
23}