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 );

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 );

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.

Related posts

1 comment on »Creating a WooCommerce product variation with the REST API«

  1. Edu

    It was super useful for me!! It is not so easy to find how to change the attributes and variations by API REST


Leave a Comment

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