WooCommerce REST API: Create Products with Attributes

Before all I also recommend you to check my basic WooCommerce REST API tutorial, where we just created and updated some simple products.

Right now I am going to show you two more specific examples. Two – because there are two types of attributes in WooCommerce – custom attributes and the ones that created in Products > Attributes menu (those are technically taxonomies).

Create a Product with Custom Product Attributes

And yes, for every example we will need a pair of Consumer Key and Consumer Secret, please read here how to get them.

$response = wp_remote_post( 
	'https://test-website/wp-json/wc/v3/products', 
	array(
		'headers' => array(
			'Authorization' => 'Basic ' . base64_encode( "$key:$secret" )
		),
		'body' => array(
  		'name' => 'My test product',
			'regular_price' => '21.99',
			'attributes' => array(
				array(
  					'name' => 'Magical',
  					'visible' => true, // default: false
  					'options' => array( 'Yes', 'No' )
				)
			)
		)
	)
);

if( 'Created' === wp_remote_retrieve_response_message( $response ) ) {
	$body = json_decode( wp_remote_retrieve_body( $response ) );
	echo 'The product ' . $body->name . ' has been created';
}

I think there is nothing to explain in the above code. After running it, if you go to the edit product page, you will see something like this on the Attributes tab:

Custom product attributes created with WooCommerce API

Create Products with Taxonomy-type Attributes

In case you would like to add a taxonomy-based attribute to a product, you will need to know the attribute ID, which can be found easily – just go to Products — Attributes page, click Edit button near the specific attribute and look at the page URL.

$response = wp_remote_post( 
	'https://test-website/wp-json/wc/v3/products', 
	array(
		'headers' => array(
			'Authorization' => 'Basic ' . base64_encode( "$key:$secret" )
		),
		'body' => array(
			'name' => 'My test product',
			'regular_price' => '21.99',
			'attributes' => array(
				// attribute 1 (custom attribute)
				array(
					'name' => 'Magical',
					'position' => 1,
					'visible' => true, // default: false
					'options' => array( 'Yes', 'No' ),
				),
				// attribute 2 (taxonomy-based attribute)
				array(
					'id' => '2',
					'position' => 0,
					'variation' => true,
					'options' => array( 'Black', 'White' ),
				)
			)
		)
	)
);

And here we are:

WooCommerce REST API create product with attributes
Misha Rudrastyh

Misha Rudrastyh

Hey guys and welcome to my website. For more than 10 years I've been doing my best to share with you some superb WordPress guides and tips for free.

Need some developer help? Contact me

Follow me on X