我需要在 WooCommerce 中更改产品的常规价格和促销价格。
我可以使用以下方式更新正常价格:
update_post_meta( $product_id, '_price', 500 );
但我也想改变销售价格。有些产品没有
_sale
元键,因此我无法对正常价格执行相同的操作。
自 WooCommerce 3 起,Woocommerce 正在迁移到自定义表,因此最好使用所有可用的 WC_Product setter 方法...对于产品价格,您将使用以下方法:
// Get an instance of the WC_Product object
$product = wc_get_product( $product_id );
$regular_price = 500; // Define the regular price
$sale_price = 465; // Define the sale price (optional)
// Set product sale price
if ( isset($sale_price) && ! empty($sale_price) ) {
$product->set_sale_price($sale_price);
$product->set_price($sale_price); // Set active price with sale price
} else {
$product->set_price($regular_price); // Set active price with regular price
}
// Set product regular price
$product->set_regular_price($regular_price);
// Sync data, refresh caches and saved data to the database
$product->save();