Create WooCommerce products in bulk with REST API

/**
 * Creates WooCommerce products in bulk with REST API.
 *
 * @see https://wpcodebook.com/snippets/create-woocommerce-products-in-bulk-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_products_rest_api( $site_url, $ck, $cs, $products_data ) {

	// Create product
	$response = wp_remote_post(
		untrailingslashit( $site_url ) . '/wp-json/wc/v3/products/batch',
		array(
			'headers' => array(
				'Authorization' => 'Basic ' . base64_encode( "{$ck}:{$cs}" ),
			),
			'body' => array(
				'create' => $products_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';

$products_data = array(
	array(
		'name'          => esc_html__( 'Hoodie' ),
		'regular_price' => 189.99,
	),
	array(
		'name'          => esc_html__( 'Hoodie with logo' ),
		'regular_price' => 199.99,
	),
);

wpcodebook_create_products_rest_api( $site_url, $ck, $cs, $products_data );

Leave a Comment