JordanBelf
JordanBelf

Reputation: 3338

Upload multiple images to a Woocommerce product

I am trying to upload various images from an URL to a given woocommerce product. The issue I am facing with my code is that, although I see that the images are being uploaded to the server, when I go to see my post I only see the last image uploaded to the gallery.

Here is my code:

function generateSecondImage($image_url, $post_id)
{
    $upload_dir = wp_upload_dir();
    $image_data = file_get_contents($image_url);
    $filename = basename($image_url);
    if (wp_mkdir_p($upload_dir['path'])) {
        $file = $upload_dir['path'] . '/' . $filename;
    } else {
        $file = $upload_dir['basedir'] . '/' . $filename;
    }

    file_put_contents($file, $image_data);

    $wp_filetype = wp_check_filetype($filename, null);
    $attachment = array(
        'post_mime_type' => $wp_filetype['type'],
        'post_title' => sanitize_file_name($filename),
        'post_content' => '',
        'post_status' => 'inherit',
    );
    $attach_id = wp_insert_attachment($attachment, $file, $post_id);
    require_once ABSPATH . 'wp-admin/includes/image.php';
    $attach_data = wp_generate_attachment_metadata($attach_id, $file);
    $res1 = wp_update_attachment_metadata($attach_id, $attach_data);
    $res3 = update_post_meta($post_id, '_product_image_gallery', $attach_id);

}

And here is how I call the function

 for ($j=1; $j <$picCount ; $j++) { 
 generateSecondImage($pic[$j]->url, $post_id);
 }

I am thinking that maybe, res3 is overwriting the gallery and showing only the last image posted, but if that is the case, how would I tell wordpress to include all of the images in the for loop?

Upvotes: 1

Views: 2073

Answers (2)

WP Developer
WP Developer

Reputation: 1

$upload_dir = wp_upload_dir();
        $attchmentIds = [];
        foreach ($_FILES['productImages']['tmp_name'] as $key => $fileTmpName) {

            if ($fileTmpName) {
                $imageName = $_FILES['productImages']['name'][$key];
                $imageData = file_get_contents($fileTmpName);
                $upload_path = $upload_dir['path'] . '/' . $imageName;
                $imageType
                    = $_FILES['productImages']['type'][$key];
                if (file_put_contents($upload_path, $imageData) !== FALSE) {

                    $attachment         =   array(
                        'post_mime_type' => $imageType,
                        'post_title'     =>  $imageName,
                        'post_status'    => 'inherit',
                        'guid'           => $upload_dir['url'] . '/' . $imageName
                    );

                    $attachment_id = wp_insert_attachment($attachment, $upload_path);

                    $attachment_data = wp_generate_attachment_metadata($attachment_id, $upload_path);
                    wp_update_attachment_metadata($attachment_id, $attachment_data);

                    if ($key == $featured_image_key) {
                        $product->set_image_id($attachment_id);
                    } else {
                        // echo $attachment_id . "\n";
                        $attchmentIds[] = $attachment_id;
                    }
                    $product->set_gallery_image_ids($attchmentIds);
                }
            }
        }
        $product->save();
        $productId = $product->get_id();

The uploading of multiple product images using file_get_contents() to get image data and file_put_contents() to put image data as specified path , saving them to the WordPress media library, and associating them with a WooCommerce product. It sets the featured image and gallery images based on the provided input.

Upvotes: 0

JordanBelf
JordanBelf

Reputation: 3338

Finally managed to solve it!

Here is my final code. My upload function goes like this:

function generateSecondImage($image_url, $post_id)
{
    $upload_dir = wp_upload_dir();
    $image_data = file_get_contents($image_url);
    $filename = basename($image_url);
    if (wp_mkdir_p($upload_dir['path'])) {
        $file = $upload_dir['path'] . '/' . $filename;
    } else {
        $file = $upload_dir['basedir'] . '/' . $filename;
    }

    file_put_contents($file, $image_data);

    $wp_filetype = wp_check_filetype($filename, null);
    $attachment = array(
        'post_mime_type' => $wp_filetype['type'],
        'post_title' => sanitize_file_name($filename),
        'post_content' => '',
        'post_status' => 'inherit',
    );
    $attach_id = wp_insert_attachment($attachment, $file, $post_id);
    require_once ABSPATH . 'wp-admin/includes/image.php';
    $attach_data = wp_generate_attachment_metadata($attach_id, $file);
    $res1 = wp_update_attachment_metadata($attach_id, $attach_data);

    echo "Attach ID is".$attach_id;
    return $attach_id;

}

And then I had to create a comma-separated list of the IDs and add it to the add_post_meta

So my loop changed to this:

for ($j=1; $j <$picCount ; $j++) { 
$attarray[] = generateSecondImage($pic[$j]->url, $post_id);
}

$commaList = implode(', ', $attarray);
$res3 = add_post_meta($post_id, '_product_image_gallery', $commaList);

Hope this helps anyone else looking for a solution.

Upvotes: 2

Related Questions