Creating a WooCommerce product variation with the REST API

Like adding a product via the REST API is creating a product variation done relatively quickly – I use the PHP library for that, like in my last week’s post.

Requirements for adding a variation

To make adding a variation work, we need to add the wanted attributes to the product first. This can look something like that while adding a product (my post from last week was about that):

$prod_data = [ 'name' => 'A great product', 'type' => 'variable', 'description' => 'A very meaningful product description', 'images' => [ [ 'src' => 'https://shop.local/path/to/image.jpg', 'position' => 0, ], ], 'categories' => [ [ 'id' => 1, ], ], 'attributes' => [ [ 'id' => 5, 'variation' => true, 'visible' => true, 'options' => [ 'S', 'M', 'L' ], ], ], ]; $product = $this->woocommerce->post( 'products', $prod_data );
Code language: PHP (php)

We set an array of attributes for the attributes key (just the size in the example) and can specify if this attributes should be available for variations via variation. With options, we define the available options for the variations – those attribute terms must exist before adding the product, like the attribute.

Besides that, we set the type of the product to variable.

Adding a product variation

After we meet the requirements, we can create a variation with the following code:

$variation_data = [ 'regular_price' => '15.00', 'image' => [ 'src' => 'https://shop.local/path/to/image_size_l.jpg', ], 'attributes' => [ [ 'id' => 5, 'option' => 'L', ], ], ]; $this->woocommerce->post( "products/$product->id/variations", $variation_data );
Code language: PHP (php)

We define the price, set an image and the size. For specifying the size, we pass the id of the attribute and the label of the option as an array inside the array of attributes. We use the REST API endpoint products/$product->id/variations – we can get the product’s ID via $product->id here, because we saved the call of the products endpoint for creating the product in the $product variable.

And that is it – we should have created a variable product with a variation.

22 reactions on »Creating a WooCommerce product variation with the REST API«

  1. Thank you for this in-depth tutorial. I am trying to work on product variations but not getting the actual results as I have already gone through several resources and following this resource https://wpitech.com/woocommerce-product-variation/ to implement the product variation process. Can you please describe me further how to do this? This is the code that I think is somehow wrong. Is there any other way to set product variations?

    $variation_id = woo_insert_post( $variation_post );
    $variation = new WooCommerce_Product_Variation( $variation_id );
    foreach ($variation_data['attributes'] as $attribute => $term_name )

    1. Hi,

      I guess it would be better to ask that question under the article where the code is from – I cannot help you with that, because I do not know the code (and do not have the time to dive into it).

      Best,
      Florian

  2. Hey Florian,

    Thanks for the article! I think this is closest I got trying to achieve the following..

    I've already loaded all products to WooCommmerce, and all attributes (size, colour etc.) are entered. Further, checkbox for the "used for variations" is selected for the relevant ones (there are a few that are not used for variations, they are there just for info).

    So, can I use above code to generate all variations for all products? There are 1000+ products, and some variations would exceed 50, so doing this manually is a massive job. I'm trying to find a way to automate that part, and above article sounds like it does exactly that, although I'm not quite sure how to implement it.

    I would appreciate your comment and guidance on how this code could be applied.

    Many thanks in advance!

  3. Hello Florian,
    I was reading your article, Would you mind if I asked some advice.

    When I update a product using the API with the attribute term that includes a space e.g "Brand 1, Brand 2", it creates three attributes for me, "Brand" , "2" and "1". What am I doing wrong. Single attributes are fine.

    I send it to woocommerce the following

      [3] => Array
            (
                [id] => 2
                [name] => brands
                [visible] => 1
                [variation] => 1
                [options] => Brand 1,Brand 2
            )

    and it does this.

      [attributes] => Array
            (
                [0] => stdClass Object
                    (
                        [id] => 2
                        [name] => brands
                        [position] => 0
                        [visible] => 1
                        [variation] => 1
                        [options] => Array
                            (
                                [0] => 1
                                [1] => 2
                                [2] => Brand
                            )
                    )
    1. Hi Adam,

      when I see it correct, the docs say that the options are an array. So you would need to specify it like follows:

      [options] => [ 'Brand 1' ,'Brand 2' ]

      Maybe that works.

      Best,
      Florian

  4. Hey!

    I end up with a product with empty attributes, when I am using this code.
    Any suggestions, what could be wrong?

    [attributes] => Array
    (
    )

    [default_attributes] => Array
    (
    )

    [variations] => Array
    (
    )

      1. Hi!
        it´s an exact copy from this blogpost:

        $prod_data = [
        	'name'        => 'A great product',
        	'type'        => 'variable',
        	'description' => 'A very meaningful product description',
        	'images'      => [
        		[
        			'src'      => 'https://pathTo.jpg',
        			'position' => 0,
        		],
        	],
        	'categories'  => [
        		[
        			'id' => 1,
        		],
        	],
        	'attributes'  => [
        		[
        			'id'        => 5,
        			'variation' => true,
        			'visible'   => true,
        			'options'   => [ 'S', 'M', 'L' ],
        		],
        	],
        ];
        
        $this->product = $this->api->post( 'products', $prod_data );
        
        		$variation_data = [
        		'regular_price' => '35.00',
        		'image'         => [
        			'src' => 'https://pathTo.jpg',
        		],
        		'attributes'    => [
        			[
        				'id'     => 5,
        				'position' => 0,
        				'option' => 'S',
        			],
        		],
        	];
        	
        	$id = $this->product->id;
        	
        	$this->api->post( "products/$id", $variation_data );
          1. no, I thought this would create the product including attributes and variation.

            I changed the code to:

            'attributes'  => [
            		[			
            			'name' => 'Auswahl',
            			'variation' => true,
            			'visible'   => true,
            			'options'   => [ 'S', 'M', 'L' ],
            		],
            	],

            and variation_data:

            'attributes'    => [
            		[
            			'name' => 'Auswahl',
            			'option' => 'L',
            		],
            	],

            and now it is working fine.

            Thanks for your support.

  5. Hi,

    Have been trying to sort this out. My variation does not seem to associate to the attribute. I've tried multiple options including the id and name and options (color). But nothing seems to stick.

    When creating the product my Attributes are as follows :

    "attributes":[
    {
    "id":"1",
    "name":"Color",
    "visible":True,
    "variation":True,
    "options":[
    "Colour Light red",
    "Colour Fuchsia",
    "Colour Grey",
    "Colour Black",
    "Colour Pink"
    ]
    }
    ]

    Here is on the variation:
    {
    "regular_price":"84.24",
    "sale_price":"84.24",
    "manage_stock":True,
    "stock_status":"instock",
    "stock_quantity":"5",
    "image":{
    "id":7462
    },
    "attritubes":[
    {
    "id":1,
    "name":"Color",
    "option":"Colour Pink"
    }
    ]
    }

    The variation is created but not associated to the attribute (color). Any suggestions would be helpful. I'm using python woocommerce API.

    1. You will want to check the spelling of the attributes you are using for the variation. It should say "attribute" and not "attritubes" as it is written in the example json you've posted

    2. For anyone stumbling on this issue, it took me a while to find out, in the variations post also add the attribute 'name', as follows:

      attributes: [
      {
      id: variation.attributeId,
      name: "TheNameOfTheAttribute",
      option: variation.option
      }
      ]

  6. Hi,
    I'm having some trouble when trying to create a product using Postman..
    I can't find a way to pass the categories. It keeps showing "rest_invalid_param" error code, with error message "categories[0] not object type".

    What I actually need to achieve is to create a product using a java wrapper that takes the parameters from a map, but I keep getting the same error.
    I assume that once I get it to work on Postman, I will be able to make it work in java as the only thing I have to do is to pass the same parameter value.

    Any suggestion?

  7. Hi Florian

    I am using this code in a custom created file and this file has only a single function. How do I use $this->woocommerce in my custom function?

    please help.

    $variation_data = [
    'regular_price' => '15.00',
    'image' => [
    'src' => 'https://shop.local/path/to/image_size_l.jpg',
    ],
    'attributes' => [
    [
    'id' => 5,
    'option' => 'L',
    ],
    ],
    ];

    $this->woocommerce->post( "products/$product->id/variations", $variation_data );

Leave a Reply

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