Categories
CMS Mastering Development Wordpress

Woocommerce api: create product with images – bad request

I am trying to create a product with images via the Woocommerce Rest API but I get bad request:

Here is how I am preparing the images array:

//IMAGES
    $images = [];
    //Get the featured image
    $featured_image_url = wp_get_attachment_image_src( get_post_thumbnail_id($post_id));
    //and push it in the images array with position = 0 (featured)
    array_push($images, ['src' => $featured_image_url[0], 'position' => 0]);
    //Get All the images
    $attachmentIds = $product->get_gallery_attachment_ids();
    $pos = 1;
    foreach( $attachmentIds as $attachmentId )
    {   
        array_push($images, ['src' => wp_get_attachment_image_src( $attachmentId ), 'position' => $pos]);
        $pos++;
    }

This is code is being called after a product is published, and when I am publishing a product with featured image and 2 more images in its gallery I get this as the $images array:

Array
(
    [0] => Array
        (
            [src] => http://src_image-150x150.jpg
            [position] => 0
        )

)

I get only the featured image, and I receive bad request when I send this post request to create the product. If I comment out the images attribute of the request then the product is created successfully.

Leave a Reply

Your email address will not be published. Required fields are marked *