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

nho*_*ay4 3 php wordpress cart woocommerce hook-woocommerce

我正在尝试根据艺术品总数中的特定金额增加费用。我想显示购物车总额是否等于或大于总额“ $$$”,请添加费用,否则不添加。

我知道这可以将其加到总计中,但是我不认为它正在检查它是否低于美元金额。

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' );
Run Code Online (Sandbox Code Playgroud)

我做错了什么?

Loi*_*tec 5

woocommerce_cart_calculate_fees动作挂钩中,请WC()->cart->total始终返回0,因为此挂钩会在购物车总计计算之前触发……

您最好WC()->cart->cart_contents_total改用。

而且,购物车对象已经包含在此挂钩中,因此您可以将其作为参数添加到挂钩函数中。
您也不需要使用此钩子woocommerce_after_cart_item_quantity_update

这是您重新访问的代码:

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 );
}
Run Code Online (Sandbox Code Playgroud)

代码在您的活动子主题(或主题)的functions.php文件中,或者在任何插件文件中。

此代码已经过测试并且可以工作。