How to add image attachment to post from a single meta key (Woocommerce)

I’m using Woocommerce for products. All products are imported automatically by a plugin.
Currently when i want to attach an image to a product (a post type) i have to use “Featured image” to display the image on the website. This is all manual work.

Once i save the image, the image is saved to the database in table wp_posts, the post_type is “attachment”, the post_mime_type is “image/jpeg”, the post_parent is the postID.

Read More
ID    post_author   post_title      post_status post_name      post_parent guid                            post_type   post_mime_type
200   1             Niceimagename   inherit     Niceimagename  116         http://domain.com/imageurl      attachment  image/jpeg            

What code do i have to add to my functions.php that if a post gets saved or updated that it uses the value in meta key “_image” to attach the image to the post like the sample above?

Related posts

Leave a Reply

1 comment

  1. I got it now using the following code:

    //featured image from postmeta
    function postmeta_img_update() {
    global $post;
    // If Custom Post Meta Field for a Image/Thumnail Exists
    if( get_post_meta($post->ID, "_image", true):
    
    // Get Image Location and File Extention
    $img = get_post_meta($post->ID, "_image", true);
    $ext = substr(strrchr($img,'.'),1);
    
    // WordPress Upload Directory to Copy to (must be CHMOD to 777)
    $uploads = wp_upload_dir();
    $copydir = $uploads['path']."/";
    
    // Code to Copy Image to WordPress Upload Directory (Server Must Support file_get_content/fopen/fputs)
    $data = file_get_contents($img);
    $filetitle = strtolower(str_replace(array(' ', '-', '.', '(', ')', '!', '@', '#', '$', '%', '^', '&', '*', '_', '=', '+', '/', '"'), "-", get_the_title()));
    $file = fopen($copydir . "$filetitle-$post->ID.$ext", "w+");
    fputs($file, $data);
    fclose($file);
    // Insert Image to WordPress Media Libarby
    $filepath = $uploads['path']."/$filetitle-$post->ID.$ext";
    
    $wp_filetype = wp_check_filetype(basename($filepath), null );
    $attachment = array(
     'post_mime_type' => $wp_filetype['type'],
     'post_title' => get_the_title(),
     'post_content' => 'Image for '.get_the_title(),
     'post_status' => 'inherit'
    );
    
    wp_insert_attachment( $attachment, $filepath, $post->ID);
    
    // Get Attachment ID for Post
    global $wpdb; $attachment_id = $wpdb->get_var("SELECT ID FROM $wpdb->posts WHERE post_parent = '$post->ID' AND post_status = 'inherit' AND post_type='attachment' ORDER BY post_date DESC LIMIT 1");
    // Attached Image as Featured Thumbnail in Post
    update_post_meta($post->ID, "_thumbnail_id", $attachment_id);
    
    // Removes Custom Meta Field Image URL. This stop this function running again for the updated post.
    delete_post_meta($post->ID, "_image");
    
    endif;
    
    }
    add_action('the_post','postmeta_img_update');