Update WooCommerce product price and stock

和自甴很熟 提交于 2021-02-11 06:09:45

问题


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?


回答1:


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();
}



回答2:


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();
   }


来源:https://stackoverflow.com/questions/62812359/update-woocommerce-product-price-and-stock

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!