如何在 WooCommerce 中以编程方式设置产品的销售和正常价格

问题描述 投票:0回答:1

我需要在 WooCommerce 中更改产品的常规价格和促销价格。

我可以使用以下方式更新正常价格:

update_post_meta( $product_id, '_price', 500 );

但我也想改变销售价格。有些产品没有

_sale
元键,因此我无法对正常价格执行相同的操作。

php wordpress woocommerce product price
1个回答
0
投票

自 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(); 
© www.soinside.com 2019 - 2024. All rights reserved.