Update WooCommerce variation meta with REST API

/**
 * Updates WooCommerce variation product meta data with REST API.
 *
 * @see https://wpcodebook.com/woocommerce-rest-api-update-variation-meta/
 * @see https://woocommerce.github.io/woocommerce-rest-api-docs/
 * @see https://developer.wordpress.org/reference/functions/wp_remote_request/
 *
 * @return bool|string true on success, error message otherwise
 */
function wpcodebook_update_variation_meta_data( $site_url, $ck, $cs, $variation_id, $meta_data ) {

	// Request URL
	$product_id  = wp_get_post_parent_id( $variation_id );
	$request_url = "/wp-json/wc/v3/products/{$product_id}/variations/{$variation_id}";

	// Update variation meta data
	$response = wp_remote_request(
		untrailingslashit( $site_url ) . $request_url,
		array(
			'method'    => 'PUT',
			'sslverify' => false, // optional
			'headers'   => array(
				'Authorization' => 'Basic ' . base64_encode( "{$ck}:{$cs}" ),
			),
			'body'      => array(
				'meta_data' => $meta_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_8188e3d81427b2c74053c5ffeac4514e0e2c2092';
$cs           = 'cs_f1af48ad80b14d95fc627566975c8426595a071f';
$variation_id = 1977;
$meta_data    = array(
	array(
		'key'   => 'ean',
		'value' => '0614141123452',
	),
	array(
		'key'   => 'mpn',
		'value' => 'H2G2-42',
	),
);

wpcodebook_update_variation_meta_data( $site_url, $ck, $cs, $variation_id, $meta_data );

Leave a Comment