我有外部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 Query或带有钩子的解决方案,他们说我应该进行瞬时清理等。。。我没有一个最佳的解决方案。您能帮我什么是完成此任务的最佳解决方案吗?
答案 0 :(得分:1)
正如您所说,有很多方法。在循环内部,您可能会使用WC_Product::setPrice()
方法。作为explained here,您可以像这样使用它:
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();
}
答案 1 :(得分:1)
您可以尝试这种方式:
$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();
}