在WooCommerce 3中以编程方式设置产品销售价格

Mar*_*sen 5 php wordpress product woocommerce price

我在Woocommerce商店中开设了各种产品类别。

我想对所有属于杜鹃产品类别的产品都享受20%的折扣

目前,我要实现的全部目标是在我的functions.php中设置销售价格

它尝试如下:

    /* 
     * For a specific date, 20% off all products with product category as cuckoo clock.
     */
    function cuckoo_minus_twenty($sale_price, $product) { 
        $sale_price = $product->get_price() * 0.8;
        return $sale_price;
    }; 

    // add the action 
    add_filter( 'woocommerce_get_sale_price', 'cuckoo_minus_twenty', 10, 2 ); 
Run Code Online (Sandbox Code Playgroud)

如果在计算后将var_dump的结果转储为$ sale_price的结果,则会得到正确的答案,但是前端的价格显示会剔除正常价格,并将销售价格显示为正常价格。

在此处输入图片说明

我可以使用钩子/过滤器来实现此目的吗?

我还尝试通过以下方式设置销售价格:

$product->set_sale_price($sale_price); 
Run Code Online (Sandbox Code Playgroud)

无济于事。

Loi*_*tec 8

woocommerce_get_sale_price自 WooCommerce 3 起不推荐使用该钩子并由woocommerce_product_get_sale_price.

还缓存了产品显示的价格。当销售价格处于活动状态时,正常价格也处于活动状态。

试试这个:

// Generating dynamically the product "regular price"
add_filter( 'woocommerce_product_get_regular_price', 'custom_dynamic_regular_price', 10, 2 );
add_filter( 'woocommerce_product_variation_get_regular_price', 'custom_dynamic_regular_price', 10, 2 );
function custom_dynamic_regular_price( $regular_price, $product ) {
    if( empty($regular_price) || $regular_price == 0 )
        return $product->get_price();
    else
        return $regular_price;
}


// Generating dynamically the product "sale price"
add_filter( 'woocommerce_product_get_sale_price', 'custom_dynamic_sale_price', 10, 2 );
add_filter( 'woocommerce_product_variation_get_sale_price', 'custom_dynamic_sale_price', 10, 2 );
function custom_dynamic_sale_price( $sale_price, $product ) {
    $rate = 0.8;
    if( empty($sale_price) || $sale_price == 0 )
        return $product->get_regular_price() * $rate;
    else
        return $sale_price;
};

// Displayed formatted regular price + sale price
add_filter( 'woocommerce_get_price_html', 'custom_dynamic_sale_price_html', 20, 2 );
function custom_dynamic_sale_price_html( $price_html, $product ) {
    if( $product->is_type('variable') ) return $price_html;

    $price_html = wc_format_sale_price( wc_get_price_to_display( $product, array( 'price' => $product->get_regular_price() ) ), wc_get_price_to_display(  $product, array( 'price' => $product->get_sale_price() ) ) ) . $product->get_price_suffix();

    return $price_html;
}
Run Code Online (Sandbox Code Playgroud)

代码位于活动子主题(活动主题)的 function.php 文件中。

经过测试并适用于单个产品、商店、产品类别和标签存档页面。

继续:以
编程方式设置产品销售价格后 Woocommerce 购物车项目价格错误