[英]Update WooCommerce product price and stock
我有外部 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')
);
在此之后,我需要更新 WooCommerce 中产品的价格和数量。 (上面的数组代码是 WC 中的 SKU)。
之后我的代码如下:
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 查询或带有一些钩子,他们说我应该进行临时清洁等......我无法想出一个最好的解决方案。 您能帮我完成这项任务的最佳解决方案吗?
正如你所说,有很多方法。 在你的循环中,你可能会使用WC_Product::setPrice()
方法。 如此处所述,您可以像这样使用它:
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();
}
你可以这样试试:
$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.