【问题标题】:Add a percentage Fee with a fixed Fee to Woocommerce向 Woocommerce 添加具有固定费用的百分比费用
【发布时间】:2018-10-16 13:32:34
【问题描述】:

在 Woocommerce 中,我想在结帐页面添加 3% 的手续费和 30 美分的“固定”费用。

我已经设法使用下面提到的代码添加了处理费:

add_action( 'woocommerce_cart_calculate_fees', 'woocommerce_custom_surcharge' );
function woocommerce_custom_surcharge() {
    global $woocommerce;

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

    $percentage = 0.03;
    $surcharge = ( $woocommerce->cart->cart_contents_total + $woocommerce->cart->shipping_total ) * $percentage;
    $woocommerce->cart->add_fee( 'Processing Fee', $surcharge, true, '' );
}

现在,我只需要加上 30 美分的“固定”费用。我怎样才能做到这一点?

我试过了,添加:

$fee = 0.30;

但是,它对我不起作用。

【问题讨论】:

  • add_fee() 函数中有什么?它会返回一个值吗?
  • 您是否尝试将.30 添加到您的$surcharge 变量值...?
  • 我在你的代码中没有看到$fee。你是在问如何用 PHP 做数学运算?
  • @MonkeyZeus 会让你在这个网站上大吃一惊 :-) …
  • @misorude 很遗憾,这并不让我感到惊讶。每次来这里参加的理由越来越少:-/

标签: php wordpress woocommerce cart checkout


【解决方案1】:

您的代码有点过时,请尝试以下操作,这将在百分比费用中添加固定费用:

add_action( 'woocommerce_cart_calculate_fees', 'woocommerce_custom_surcharge' );
function woocommerce_custom_surcharge( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    $percentage = 0.03;
    $fixed_fee  = 0.3;

    $percentage_fee = ( $cart->cart_contents_total + $cart->shipping_total ) * $percentage;
    $surcharge  = $fixed_fee + $percentage_fee;

    $cart->add_fee( 'Processing Fee', $surcharge, true );
}

代码进入您的活动子主题(或活动主题)的 function.php 文件中。经过测试并且可以工作。

当使用这个钩子时,不需要过时的$global $woocommerce;,因为钩子函数可以使用WC_Cart对象变量作为参数......

【讨论】:

  • 您的代码运行良好!对于 100 美元以上(仅限)的订单,是否可以使此代码正常工作?
  • @UsamaShabbier 在$percentage = 0.03; 这行之前添加if( $cart->subtotal <= 100 ) return; ...您只能在此挂钩中定位小计。
  • 谢谢。你真的是一个传奇❤️很抱歉再次打扰你,但我有最后一个问题: - 我如何让这个代码只适用于小订单?我只想为小额订单(低于 100 美元)申请手续费。
【解决方案2】:

如果您需要同时添加两种附加费,使它们可以单独显示,您可以:

$percentage = 0.03;
$fixed_fee = 0.30;

$surcharge = ( $woocommerce->cart->cart_contents_total + $woocommerce->cart->shipping_total ) * $percentage;
$woocommerce->cart->add_fee( 'Processing Fee', $surcharge, true, '' );
$woocommerce->cart->add_fee( 'Fixed fee', $fixed_fee, true, '' );

如果您不需要单独显示,只需注意“处理费”包括 3% 的附加费和固定的 30 美分:

$percentage = 0.03;
$fixed_fee = 0.30;

$surcharge = (( $woocommerce->cart->cart_contents_total + $woocommerce->cart->shipping_total ) * $percentage) + $fixed_fee);
$woocommerce->cart->add_fee( 'Processing Fee', $surcharge, true, '' );

两者都应该工作。这取决于您在下游需要什么

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-06-01
    • 2019-08-26
    • 2021-11-23
    • 2021-12-17
    • 2017-01-08
    • 2016-12-20
    • 1970-01-01
    相关资源
    最近更新 更多