首页 > 解决方案 > 根据 WooCommerce 中的付款方式和购物车项目总数添加费用

问题描述

我安装了一个插件->“WooCommerce 的基于支付网关的费用和折扣”,它帮助我添加了两项费用:

问题是如果有人购买超过 300 件,我想免费送货。所以我必须取消额外费用这是我尝试过的,但没有任何反应:

function woo_remove_cart_fee() {

  $cart_items_total = WC()->cart->get_cart_contents_total();

    if ( $cart_items_total > 300 ) {
        $fees = 0 ;     
   } 

add_action( 'woocommerce_cart_calculate_fees', 'woo_add_remove_fee' );

有任何想法吗?或者关于如何让网关费用和免费送货超过限制的任何想法?

谢谢。

标签: phpwordpresswoocommercepayment-methodfee

解决方案


您不能删除插件根据购物车项目总安装量添加的费用。

由于您的插件不处理最小或最大购物车金额条件,请先从中禁用费用(或禁用插件)并改用以下内容:

add_action( 'woocommerce_cart_calculate_fees', 'fee_based_on_payment_method_and_total' );
function fee_based_on_payment_method_and_total( $cart ) {
    if ( is_admin() && ! defined('DOING_AJAX') )
        return;
        
    $threshold_amount  = 300; // Total amount to reach for no fees
    
    $payment_method_id = WC()->session->get('chosen_payment_method');
    $cart_items_total  = $cart->get_cart_contents_total();

    if ( $cart_items_total < $threshold_amount ) {
        // For cash on delivery "COD"
        if ( $payment_method_id === 'cod' ) {
            $fee = 14.99;
            $text = __("Fee");
        } 
        // For credit cards (other payment gateways than "COD", "BACS" or "CHEQUE"
        elseif ( ! in_array( $payment_method_id, ['bacs', 'cheque'] ) ) {
            $fee = 19.99;
            $text = __("Fee");
        }
    }
    
    if( isset($fee) && $fee > 0 ) {
        $cart->add_fee( $text, $fee, false ); // To make fee taxable change "false" to "true"
    }
} 

以下代码用于刷新付款方式更改的数据:

// jQuery - Update checkout on payment method change
add_action( 'wp_footer', 'custom_checkout_jquery_script' );
function custom_checkout_jquery_script() {
    if ( is_checkout() && ! is_wc_endpoint_url() ) :
    ?>
    <script type="text/javascript">
    jQuery( function($){
        $('form.checkout').on('change', 'input[name="payment_method"]', function(){
            $(document.body).trigger('update_checkout');
        });
    });
    </script>
    <?php
    endif;
}

代码位于活动子主题(或活动主题)的 functions.php 文件中。测试和工作。

相关:根据 WooCommerce 中的特定付款方式添加费用


推荐阅读