简体   繁体   English

根据WooCommerce中的特定购物车总额添加费用

[英]Add fee based on specific cart total in WooCommerce

I'm trying to add fee based on specific amount in art total. 我正在尝试根据艺术总数中的具体金额增加费用。 I want to show if the cart total is equal to or greater than total "$$$" amount add the fee, otherwise don't add. 我想显示如果购物车总数等于或大于总“$$$”金额添加费用,否则请勿添加。

I know this works adding it to total, but I don't think it's checking to see if it is below dollar amount. 我知道这可以将它添加到总数中,但我认为它不会检查它是否低于美元金额。

function woo_add_custom_fees(){

    $cart_total = 0;

    // Set here your percentage
    $percentage = 0.15;

    foreach( WC()->cart->get_cart() as $item ){ 
        $cart_total += $item["line_total"];
    }
    $fee = $cart_total * $percentage;

    if (  WC()->cart->total >= 25 ) { 

     WC()->cart->add_fee( "Gratuity", $fee, false, '' );

    }

    else {

        return WC()->cart->total;
    }
}
add_action( 'woocommerce_cart_calculate_fees' , 'woo_add_custom_fees' );
add_action( 'woocommerce_after_cart_item_quantity_update', 'woo_add_custom_fees' );

What I am doing wrong? 我做错了什么?

In woocommerce_cart_calculate_fees action hook, WC()->cart->total always return 0 , as this hook is fired before the cart total calculations… woocommerce_cart_calculate_fees动作挂钩中, WC()->cart->total总是返回0 ,因为这个挂钩在推车总计算之前被触发...

You should better use WC()->cart->cart_contents_total instead. 您最好使用WC()->cart->cart_contents_total

Also the cart object is already included in this hook, so you can add it as an argument in your hooked function. 此对象已经包含在此挂钩中,因此您可以将其作为参数添加到挂钩函数中。
Also you dont need to use this hook woocommerce_after_cart_item_quantity_update . woocommerce_after_cart_item_quantity_update需要使用这个钩子woocommerce_after_cart_item_quantity_update

Here is your revisited code: 这是您重新访问的代码:

add_action( 'woocommerce_cart_calculate_fees', 'custom_fee_based_on_cart_total', 10, 1 );
function custom_fee_based_on_cart_total( $cart ) {

    if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return;

    // The percentage
    $percent = 15; // 15%
    // The cart total
    $cart_total = $cart->cart_contents_total; 

    // The conditional Calculation
    $fee = $cart_total >= 25 ? $cart_total * $percent / 100 : 0;

    if ( $fee != 0 ) 
        $cart->add_fee( __( "Gratuity", "woocommerce" ), $fee, false );
}

Code goes in functions.php file of your active child theme (or theme) or also in any plugin file. 代码放在活动子主题(或主题)的functions.php文件中,或者放在任何插件文件中。

This code is tested and works. 此代码经过测试和运行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM