Update WooCommerce product price and stock

Viewed 2274

I have external REST API, from which I'm building an array like this:

$arr = array(
1 => array('code' => '0100686', 'qty' => '2', 'price' => '65.22'),
2 => array('code' => '0100687', 'qty' => '1', 'price' => '5.23'),
3 => array('code' => '0100688', 'qty' => '8', 'price' => '0.28')
);

After this, I need to update the price and qty of products in WooCommerce. (In above array code is SKU in WC).

Afterwards my code goes following way:

foreach ($arr as $single) {
$product_id = wc_get_product_id_by_sku($single['code']);

// I need here to update the product price
// I need here to update the product in stock

}

I searched and there are a lot of solutions out there directly via SQL Query or with some hooks and they were saying that I should make transient cleaning and etc... I was not able to come up with one best solution. Could you please help me what will be the best solution to do this task?

2 Answers

As you say, there are many ways. Inside your loop you cold maybe use the WC_Product::setPrice() method. As explained here, you can use it like:

foreach ($arr as $single) {
    $product_id = wc_get_product_id_by_sku($single['code']);
    $wcProduct = new WC_Product($product_id);

    //price in cents
    $wcProduct->set_price(300);
    $wcProduct->save();
   }

You can try this way:

$arr = array(
    array( 'code' => '0100686', 'qty' => '2', 'price' => '65.22' ),
    array( 'code' => '0100687', 'qty' => '1', 'price' => '5.23' ),
    array( 'code' => '0100688', 'qty' => '8', 'price' => '0.28' )
);
foreach ( $arr as $single ) {
    $product_id = wc_get_product_id_by_sku( $single['code'] );
    if ( ! $product_id ) {
        continue;
    }
    $product = new WC_Product( $product_id );
    if ( ! $product ) {
        continue;
    }
    $product->set_price( $single['price'] );
    $product->set_stock_quantity( $single['qty'] );
    $product->save();
}
Related