Create WooCommerce product with REST API

/**
 * Creates WooCommerce product with REST API.
 *
 * @see https://wpcodebook.com/snippets/create-woocommerce-product-with-rest-api/
 * @see https://woocommerce.github.io/woocommerce-rest-api-docs/
 * @see https://developer.wordpress.org/reference/functions/wp_remote_post/
 *
 * @return bool|string true on success, error message otherwise
 */
function wpcodebook_create_product_rest_api( $site_url, $ck, $cs, $product_data ) {

	// Create product
	$response = wp_remote_post(
		untrailingslashit( $site_url ) . '/wp-json/wc/v3/products',
		array(
			'headers' => array(
				'Authorization' => 'Basic ' . base64_encode( "{$ck}:{$cs}" ),
			),
			'body'    => $product_data,
		),
	);

	// Check for WordPress errors
	if ( is_wp_error( $response ) ) {
		return $response->get_error_message();
	}

	// Check for remote response errors
	if ( ! in_array( wp_remote_retrieve_response_code( $response ), array( 200, 201 ) ) ) {
		return wp_remote_retrieve_response_message( $response );
	}

	// Success
	return true;

}

Example:

$site_url     = 'https://example.com';
$ck           = 'ck_62febaa7cd4b48fcecfacb71e366e352faef31f3';
$cs           = 'cs_888c102733dcad0d7045ad444655c246eb55272d';
$product_data = array(
		'name'          => esc_html__( 'Hoodie' ),
		'regular_price' => 89.99,
	);

wpcodebook_create_product_rest_api( $site_url, $ck, $cs, $product_data );

Leave a Comment