1

How to set first image from $_FILES array to product woocommerce post thumbnail and the rest put into woocommerce product gallery.

I have this code:

if ( ! empty( $_FILES['thumbnail'] )  ) {
        $files = $_FILES['thumbnail'];
        foreach ($files['name'] as $key => $value){
            if ($files['name'][$key]){
                $file = array(
                'name' => $files['name'][$key],
                'type' => $files['type'][$key],
                'tmp_name' => $files['tmp_name'][$key],
                'error' => $files['error'][$key],
                'size' => $files['size'][$key]
                );
            }
            $_FILES = array("thumbnail" => $file);
            $i=1;

require_once(ABSPATH . "wp-admin" . '/includes/image.php');
require_once(ABSPATH . "wp-admin" . '/includes/file.php');
require_once(ABSPATH . "wp-admin" . '/includes/media.php');

                foreach ($_FILES as $file => $array) {
                      if ($_FILES[$file]['error'] !== UPLOAD_ERR_OK) __return_false();

                        $attachment_id = media_handle_upload($file, $post_id);
                        $vv .= $attachment_id . ",";
                        $i++;
                }
                update_post_meta($post_id, '_product_image_gallery',  $vv);
                update_post_meta($post_id,'_thumbnail_id',$attachment_id);
        }
    }

Code works, but the last (not first) image is product thumbnail and all (not rest) images are set to image gallery. Please help

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.