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

4zcjmb1e  于 5个月前  发布在  PHP
关注(0)|答案(1)|浏览(50)

我需要在WooCommerce中更改产品的常规和销售价格。
我可以使用以下方法更新常规价格:

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

字符串
但我想改变销售价格也。有些产品没有一个_sale Meta密钥,所以我不能做同样的事情,我没有正常的价格。

dwbf0jvd

dwbf0jvd1#

你实际上是在使用旧的方式来设定产品价格.有两种方法:

A)使用这种旧方法,

1.要仅设置正常价格,您应该使用:用途:

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

字符串
1.要设置销售价格和正常价格,您应该使用:用途:

update_post_meta( $product_id, '_sale_price', 450 );
update_post_meta( $product_id, '_price', 450 );
update_post_meta( $product_id, '_regular_price', 500 );

B)新的方式 (自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();

相关问题