首页 > 解决方案 > 在产品页面上为相关产品设置折扣价

问题描述

我正在尝试将产品页面上所有相关产品的价格设置为低 10% = 0.9

目标是在产品页面上提供所有相关产品的折扣,但当作为产品查看时,给出正常价格。

总体而言,这个想法是提供激励,从而产生相关产品的向上销售。

我在这里要求两件事。:在产品页面上更改相关产品的产品价格(10% 折扣)和:当相关的折扣产品从产品页面添加到购物车时,将该折扣价放入购物车并结帐。

我几乎把第一部分写下来,但我试图开始工作的代码给了我一个错误,说:

Warning: A non-numeric value encountered

到目前为止我的代码:

add_filter( 'woocommerce_get_price_html', 'related_product_price_discount', 100, 2 );
function related_product_price_discount( $price, $product ) {
    global $woocommerce_loop;

    // make sure this is a related product on product page
    if( is_product() && $woocommerce_loop['name'] == 'related' ){
        $price = $price * 0.9;
    }
    // return related product price with discount
    return apply_filters( 'woocommerce_get_price', $price );
}

标签: woocommerce

解决方案


StackOverFlow 中的规则当时是一个问题,所以我将只回答您的第一个问题,这与您的代码问题有关...

请注意,钩子woocommerce_get_price_html与显示的格式化价格有关。

为避免错误“警告:遇到非数字值”,您将使用以下内容:

add_filter( 'woocommerce_get_price_html', 'related_product_price_discount', 100, 2 );
function related_product_price_discount( $price_html, $product ) {
    global $woocommerce_loop;

    // make sure this is a related product on product page
    if( is_product() && $woocommerce_loop['name'] == 'related' ){
        $price_html = wc_price( wc_get_price_to_display( $product ) * 0.9 );
    }
    // return related product displayed discounted formatted price
    return $price_html;
}

代码在您的活动子主题(活动主题)的functions.php 文件中。测试和工作。


推荐阅读