Reputation: 1053
I need to update the product with the REST API from the live website to staging. It works well if I add a static product ID. What I need is to match products across sites with the SKU, not by the ID because it's not the same.
Any ideas on how to do it? My code is below.
add_action( 'woocommerce_update_product', 'on_product_savex', 10, 1 );
function on_product_savex( $product_id ) {
$product = wc_get_product( $product_id );
$get_main_website_product_id = get_post_meta( $product_id, '_sku', true );
$live_ck = 'ck_xxxx';
$live_cs = 'cs_xxxx';
$live_url = 'https://web.com/wp-json/wc/v3/products?sku='.$get_main_website_product_id.'&consumer_key=' . $live_ck . '&consumer_secret=' . $live_cs;
$body = array(
'name' => $product->get_name(), // product title
'status' => 'private', // product status, default: publish
'regular_price' => $product->get_regular_price(),
'sale_price' => $product->get_sale_price(),
'description' => $product->get_description(),
'sku' => $product->get_sku(),
'weight' => $product->get_weight(),
'manage_stock' => true,
'stock_quantity' => 10,
);
print_r( $body );
$raw_response = wp_remote_post( $live_url,
array(
'headers' => array( 'Content-Type' => 'application/json' ),
'timeout' => 30,
'body' => json_encode( $body ),
)
);
}
Upvotes: 3
Views: 3100
Reputation: 476
Get remote product ID first using SKU, then update the remote product with live product data.
add_action( 'woocommerce_update_product', 'on_product_savex', 10, 1 );
function on_product_savex( $product_id ) {
$product = wc_get_product( $product_id );
$product_sku = $product->get_sku();
$remote_keys = "consumer_key=xxxxxx&consumer_secret=xxxxxx";
// retrieve product ID by SKU, return product properties
$remote_get = wp_remote_get("https://web.com/wp-json/wc/v3/products?sku={$product_sku}&{$remote_keys}");
$remote_product = json_decode($remote_get['body'])[0];
$remote_product_id = $remote_product->id;
$body = array(
'name' => $product->get_name(), // product title
'status' => 'private', // product status, default: publish
'regular_price' => $product->get_regular_price(),
'sale_price' => $product->get_sale_price(),
'description' => $product->get_description(),
'sku' => $product->get_sku(),
'weight' => $product->get_weight(),
'manage_stock' => true,
'stock_quantity' => 10,
);
$raw_response = wp_remote_post( "https://web.com/wp-json/wc/v3/products/{$remote_product_id}?{$remote_keys}",
array(
"headers" => array( "Content-Type" => "application/json" ),
"timeout" => 30,
"body" => json_encode( $body ),
)
);
}
Upvotes: 3