在 WooCommerce 中根据付款方式和购物车项目总数添加费用

时间:2021-02-11 14:22:54

标签: php wordpress woocommerce payment-method fee

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

  • 信用卡支付 14,99 运费

  • 货到付款的运费为 19,99 美元

问题是,如果有人购买超过 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' );

有什么想法吗? 或者关于如何同时限制网关费用和免费送货的任何想法?

谢谢。

1 个答案:

答案 0 :(得分:0)

您无法删除插件根据购物车项目总装载量添加的费用。

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

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 文件中。经测试有效。

相关:Add fee based on specific payment methods in WooCommerce