ssaltman
ssaltman

Reputation: 3713

Woocommerce API - add additional images

I am trying to add another image to a product using the Woocommerce API.

However, the API overwrites the existing image(s). I have tried with no ID, no title, unique ID, etc.

Is there a way to have it append a new image, not touching the existing image?

{"images": [
    {
        "title": "temp1",
        "position": 3,
        "src": "https://www.example.com/myimage.jpg"
    }]}

Turns out that you can use an existing image if you use the internal post ID of the image as the ID tag:

{ "images": [ { "id" : 587 } ] } This will overwrite the existing image.

So, if I can figure out a way to get all the image ids of the product, I can re-add them all and append the new image onto the end...

see: WooCommerce API creates images in media even if they exist

Upvotes: 0

Views: 350

Answers (1)

ssaltman
ssaltman

Reputation: 3713

So I couldn't figure out how to stop woocommerce from overwriting all the images when I wanted to add one, so I wrote code that appends a new image onto the list of images.

//GET CURRENT IMAGE IDs FOR A PRODUCT AND BUILD JSON OF THEM

    $product_id = '652';
    $product = new WC_product($product_id);
    $attachment_ids = $product->get_gallery_image_ids();
    array_unshift($attachment_ids, get_post_thumbnail_id($product_id));

//BUILD JSON OF EXISTING IMAGE IDS
    foreach( $attachment_ids as $attachment_id ) {
    $json_images .= '{"id":' . $attachment_id . '}';
    $json_images .= ($i<count($attachment_ids) ? ',' : '');
    }
    echo "<br>" . $json_images;

//POST AN IMAGE TO AN AUCTION
    $host = 'https://beta.blohbloh.com/wp-json/wc/v3/products/' . $product_id;
    $consumer_key='ck_2364';
    $consumer_secret='cs_12ce';

//NEEDS TO INCLUDE ALL PREVIOUS IMAGE IDS IN JSON FORMAT
    $payload = '{"images": [';
    $payload .=  $json_images;
    $payload .= '{"src":';
//sample image to append
    $payload .= '"https://somesite.com/someimage.jpg"';
    $payload .= '}]}';

    $process = curl_init($host);
    curl_setopt($process, CURLOPT_HTTPHEADER, array('Content-Type: application/json', $additionalHeaders));
    curl_setopt($process, CURLOPT_HEADER, 1);
    curl_setopt($process, CURLOPT_USERPWD, $consumer_key . ":" . $consumer_secret);
    curl_setopt($process, CURLOPT_TIMEOUT, 30);
    //curl_setopt($process, CURLOPT_POST, 1);
    //curl_setopt($process, CURLOPT_POSTFIELDS, $payload);

    curl_setopt($process, CURLOPT_CUSTOMREQUEST, "PUT");
    curl_setopt($process, CURLOPT_POSTFIELDS,$payload);

    curl_setopt($process, CURLOPT_RETURNTRANSFER, TRUE);
    $return = curl_exec($process);
    curl_close($process);

Upvotes: 1

Related Questions