questions

Add fee based on payment methods and cart items total in WooCommerce

Rate this post

I have a plugin installed -> “Payment Gateway Based Fees and Discounts for WooCommerce” which helped me add two fees:

  • 14,99 delivery fee on Card Payment
  • 19,99 delivery fee on Cash on delivery

The problem is that I want to give free delivery if someone buys over 300 let’s say. So i have to remove the extra fees This is something that I’ve tried, but nothing happend:

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

Any ideas? Or any ideas on how to have both the Gateway fees and the free shipping over a limit?

Thanks.

 

✔️Solution:

You can’t delete fees added by a plugin based on cart items total mount.

As your plugin doesn’t handle a min or max cart amount condition, disable the fees first from it (or disable the plugin) and use instead the following:

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"
    }
} 

And the following code to refresh data on payment method change:

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

Code goes in functions.php file of the active child theme (or active theme). Tested and works.

Leave a Reply

Your email address will not be published.

Back to top button