更新 WooCommerce 产品价格和库存 [英] Update WooCommerce product price and stock

查看:35
本文介绍了更新 WooCommerce 产品价格和库存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有外部 REST API,我正在构建这样的数组:

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')
);

此后,我需要更新 WooCommerce 中产品的价格和数量.(上面的数组代码是WC中的SKU).

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

之后我的代码如下:

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

}

我搜索了很多解决方案,直接通过 SQL 查询或一些钩子,他们说我应该进行临时清理等等......我无法想出一个最佳解决方案.你能帮我完成这项任务的最佳解决方案是什么吗?

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?

推荐答案

你可以试试这个:

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

这篇关于更新 WooCommerce 产品价格和库存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆