【问题标题】:Add fee based on specific cart total in WooCommerce根据 WooCommerce 中的特定购物车总数添加费用
【发布时间】:2017-09-06 19:04:17
【问题描述】:

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

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

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

我做错了什么?

【问题讨论】:

  • else 部分是“下面”

标签: php wordpress woocommerce cart hook-woocommerce


【解决方案1】:

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

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

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

【讨论】:

  • 谢谢!这绝对有帮助
  • 如何在此代码中添加选择表单以选择所需的值? :) 谢谢!
  • @AlexLee 见those related threads
猜你喜欢
  • 1970-01-01
  • 2018-07-23
  • 1970-01-01
  • 1970-01-01
  • 2021-08-25
  • 1970-01-01
  • 2020-01-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多