简体   繁体   English

更新 WooCommerce 产品价格和库存

[英]Update WooCommerce product price and stock

I have external REST API, from which I'm building an array like this:我有外部 REST API,我从中构建一个这样的数组:

$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.在此之后,我需要更新 WooCommerce 中产品的价格和数量。 (In above array code is SKU in WC). (上面的数组代码是 WC 中的 SKU)。

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.我搜索了很多解决方案,直接通过 SQL 查询或带有一些钩子,他们说我应该进行临时清洁等......我无法想出一个最好的解决方案。 Could you please help me what will be the best solution to do this task?您能帮我完成这项任务的最佳解决方案吗?

As you say, there are many ways.正如你所说,有很多方法。 Inside your loop you cold maybe use the WC_Product::setPrice() method.在你的循环中,你可能会使用WC_Product::setPrice()方法。 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();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM