Delete all Product Variations Using REST API

Recently I have found this question on the internet and since I was doing exactly the same when developing WooCommerce functionality for my crossposting plugin, I decided to create a small guide for you.

The long story short we will need two REST API requests here:

I think the most clear way here would be to create a function for that, let’s say for example rudr_delete_all_variations() or something.

Let’s do it:

function rudr_delete_all_variations( $product_id, $store ) {
	
	// first of all let's get variations of a product
	$response = wp_remote_get(
		add_query_arg(
			array(
				'per_page' => 50,
				'page' => 1,
				'status' => 'any', // publish or private
			),
			"{$store[ 'url' ]}/wp-json/wc/v3/products/{$product_id}/variations"
		),
		array(
			'headers' => array(
				'Authorization' => 'Basic ' . base64_encode( "{$store[ 'login' ]}:{$store[ 'pwd' ]}" )
			)
		)
	);
	
	$variations = json_decode( wp_remote_retrieve_body( $response ), true );
	if( $variations ) {
		return false;
	}
	
	$variations_ids = wp_list_pluck( $variations, 'id' );
	
	// now remove the variations in a single batch
	wp_remote_post(
		"{$store[ 'url' ]}/wp-json/wc/v3/products/{$product_id}/variations/batch",
		array(
			'headers' => array(
				'Authorization' => 'Basic ' . base64_encode( "{$store[ 'login' ]}:{$store[ 'pwd' ]}" )
			),
			'body' => array( 'delete' => $variations_ids )
		)
	);
	
}

What we’re doing inside the function:

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