更新 WooCommerce 产品价格和库存
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()
方法。作为 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();
}
你可以这样试试:
$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();
}
我有外部 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()
方法。作为 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();
}
你可以这样试试:
$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();
}