【问题标题】:Get the product object from sku and update the price in WooCommerce从 sku 获取产品对象并在 WooCommerce 中更新价格
【发布时间】:2019-05-29 04:28:34
【问题描述】:
如何通过函数文件中的 product_id 更新产品?
我尝试使用以下代码但没有成功:
$_pf = new WC_Product_Factory();
$product_id = wc_get_product_id_by_sku( $sku );
$_product = $_pf->get_product($product_id);
$_product->set_price('225');
【问题讨论】:
标签:
php
wordpress
object
methods
woocommerce
【解决方案1】:
从 WooCommerce 3 开始,new WC_Product_Factory() 和 get_product() 方法已被弃用,并由函数 wc_get_product() 替换。
要更新价格,您必须更新价格和正常价格(或价格和销售价格)...
另外,save() 方法是最后抓取数据所必需的。
因此,要从现有产品 SKU 获取 WC_Product 对象并在其上使用任何可用方法,请执行以下操作:
$new_price = '225'; // New price
$_product_id = wc_get_product_id_by_sku( $sku );
if ( $_product_id > 0 ) {
// Get an instance of the WC_Product Object
$_product = wc_get_product( $_product_id );
$_product->set_regular_price($new_price); // Set the regular price
$_product->set_price($new_price); // Set the price
$_product->save(); // Save to database and sync
} else {
// Display an error (invalid Sku
printf('Invalid sku "%s"… Can not update price.', $sku);
}
经过测试并且有效。