Search code examples
phpwordpresswoocommerceproduct-quantityproduct-variations

woocommerce api for variation stock update by variation id


I want to update Woocommerce variation product stock by using variation id.

I tried but that update only main inventory Stock quantity not updating variations quantity. This is my code:

$product_id = 7559;
$variance_id = 122;
$get_stocks = $woocommerce->get('products/'.$product_id);
$stock_quantity_old = $get_stocks["stock_quantity"];
$data = [
        'stock_quantity' => $stock_quantity_old - 1
    ];
$result = $woocommerce->put('products/'.$product_id, $data);    

This code only updates the main inventory stock quantity. I want to update variation quantity.


Solution

  • First you need to set manage_stock to true then use stock_quantity.please use below code.

    $product_id = 7559;
    $variance_id = 122;
    $get_stocks = $woocommerce->get('products/'.$product_id);
    $stock_quantity_old = $get_stocks["stock_quantity"];
    $data = [
            'manage_stock' => true,
            'stock_quantity' => $stock_quantity_old - 1
        ];
    $result = $woocommerce->put('products/'.$product_id.'/variations/'.$variance_id, $data);