WooCommerce REST API – Create Products with Attributes

There are two types of attributes in WooCommerce – custom attributes and predefined ones. Custom attributes can be created individually on the product pages, to create a predefined attribute, go to Products — Attributes in admin menu.

Create a Product with Custom Product Attributes

Read more here how to get a pair of consumer key and secret.


$api_response = wp_remote_post( 'https://rudrastyh.com/wp-json/wc/v2/products', array(
	'headers' => array(
		'Authorization' => 'Basic ' . base64_encode( 'KEY:SECRET' )
	),
	'body' => array(
    		'name' => 'My test2',
  		'regular_price' => '21.99',
		'attributes' => array(
			array(
      				'name' => 'Color', // parameter for custom attributes
      				'visible' => true, // default: false
      				'options' => array(
        				'black',
        				'blue'
				)
			)
		)
	)
) );

$body = json_decode( $api_response['body'] );
//print_r( $body );

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

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

Add Predefined Attributes to already Existing Products

If you want to use already existing attribute, you have to specify its ID which can be found on the Products — Attributes page, just find the attribute you need, click the Edit button and look at the URL.


$api_response = wp_remote_post( 'https://rudrastyh.com/wp-json/wc/v2/products/PRODUCT ID', array(
	'headers' => array(
		'Authorization' => 'Basic ' . base64_encode( 'KEY:SECRET' )
	),
	'body' => array(
		'attributes' => array(
			array(
      				'name' => 'Color',
				'position' => 1,
      				'visible' => true, // default: false
      				'options' => array(
        				'black',
        				'blue'
				)
			),
			array(
      				'id' => '2',
				'position' => 0,
				'variation' => true, // for variative products in case you would like to use it for variations
      				'options' => array(
        				'Big',
					'SuperBig' // if the attribute term doesn't exist, it will be created
				)
			)
		)
	)
) );

$body = json_decode( $api_response['body'] );
//print_r( $body );

if( wp_remote_retrieve_response_message( $api_response ) === 'OK' ) {
	echo 'The product ' . $body->name . ' has been updated';
}
Product Attributes created with API
Misha Rudrastyh

Misha Rudrastyh

I develop websites since 2008, so it is total of 13 years of experience, oh my gosh. Most of all I love love love to create websites with WordPress and Gutenberg, some ideas and thoughts I share throughout my blog.

Need some developer help? Contact me