How to upload images from wordpress front-end (the first image must be thumbnail and the rest without first must be in gallery woocommerce product)

Question

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

--------------------------------------------------

>>> Share a link to this question, just copy and paste the code bellow on your web page <<<

<a href="https://www.wptricks.com/question/how-to-upload-images-from-wordpress-front-end-the-first-image-must-be-thumbnail-and-the-rest-without-first-must-be-in-gallery-woocommerce-product/">

How to upload images from wordpress front-end (the first image must be thumbnail and the rest without first must be in gallery woocommerce product)</a>
0
, , , Mariusz 3 days 0 Answers 16 views 0

Leave an answer