根据 WooCommerce 中的特定购物车总数添加费用 [英] Add fee based on specific cart total in WooCommerce

查看:30
本文介绍了根据 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' );

我做错了什么?

推荐答案

woocommerce_cart_calculate_fees 动作钩子中,WC()->cart->total 总是返回 0,因为这个钩子在购物车总数计算之前被触发......

In woocommerce_cart_calculate_fees action hook, WC()->cart->total always return 0, as this hook is fired before the cart total calculations…

您最好使用 WC()->cart->cart_contents_total 代替.

You should better use WC()->cart->cart_contents_total instead.

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

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.

这是您重新访问的代码:

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 );
}

代码位于活动子主题(或主题)的 functions.php 文件中,或者也位于任何插件文件中.

此代码已经过测试且有效.

This code is tested and works.

这篇关于根据 WooCommerce 中的特定购物车总数添加费用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆