【问题标题】:Woocommerc if two products in cart make a set priceWoocommerce 如果购物车中的两种产品定价
【发布时间】:2016-10-14 18:00:29
【问题描述】:

当购物车的数量是 2 的倍数时,我正在尝试为购物车的总价格添加折扣;我有一些代码,每个产品只允许一个数量,我计划有 9 个产品。

目前价格为 17 美元/件;如果用户添加了两个产品,那么总计应该是 30 美元,这应该反映在每 2 个数量的倍数上(意思是 3 个产品,价格是 47 美元,但是 4 个产品,价格是 60 美元)。

下面是我的代码。出于某种原因,当我在购物车中有一件产品时,它会将总额设置为 30 美元。

function custom_price_function( $total, $cart ) {
    //if( $cart->cart_contents_count = 2 && $cart->cart_contents_count >= 80 )
    if( $cart->cart_contents_count = 2 )
        $total = 30;
    return $total;
}
add_filter( 'woocommerce_calculated_total', 'custom_price_function', 10, 2 );

【问题讨论】:

    标签: php wordpress function woocommerce


    【解决方案1】:

    这样的事情应该可以工作:

    function calculate_total($total, $cart) {
    
        if($cart->cart_contents_count == 1){
            return $total;
        }
        $to_discount = 0;
        for($x = 0; $x <= $cart->cart_contents_count; $x ++){
            if($x % 2 === 0){
                $to_discount += 2;
            }
    
            if($cart->cart_contents_count == $x && $x % 2 === 0){
                $to_discount += 2;
            }
        }
    
        return $new_price - $to_discount;;
    }   
    add_filter( 'woocommerce_calculated_total', 'calculate_total', 10, 2 );
    

    我们所做的是根据购物车中的商品总数进行计算。您可以将其扩展为更具动态性。但它现在可以满足您的需求

    简单测试:

    for($x = 1; $x < 10; $x++ ){
        echo calculate_total(17 * $x, $x) . "\n";
    }
    

    输出:

    17
    30
    47
    62
    79
    94
    111
    126
    143
    

    【讨论】:

    • 谢谢,这太棒了。我注意到,当我在购物车中有 2 个产品时,它仍然很短(例如,2 个产品 = 32,而不是 30,4 个产品 = 64,而不是 60)。我试着玩弄它(主要是$single_price - 2 if 语句,如$single_price - (2*$cart-&gt;cart_contents_count)),但我做错了。
    • 也许我忽略了一些东西..让我检查一下嘿嘿
    • 酷,谢谢。我将如何使它成为17, 30, 47, 60, 77, 90
    • 感谢更新代码。看来您删除了 $new_pricecode 所以现在它没有声明。
    猜你喜欢
    • 2017-08-07
    • 1970-01-01
    • 1970-01-01
    • 2017-04-06
    • 2020-11-15
    • 2018-02-17
    • 2021-07-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多