Add fee for Cash on delivery payment method (cod) in Woocommerce

亡梦爱人 提交于 2019-12-05 16:01:00

It is not possible for cart page as all payment methods are only available on Checkout page.

// Add a custom fee based o cart subtotal
add_action( 'woocommerce_cart_calculate_fees', 'custom_handling_fee', 10, 1 );
function custom_handling_fee ( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    if ( 'cod' === WC()->session->get('chosen_payment_method') ) {
        $fee = 5;
        $cart->add_fee( 'Handling', $fee, true );
    }
}

You will need the following to refresh checkout on payment method change, to get it work:

// jQuery - Update checkout on methode payment change
add_action( 'wp_footer', 'custom_checkout_jqscript' );
function custom_checkout_jqscript() {
    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 function.php file of your active child theme (or active theme). tested and works.

Other payment methods:
- For Bank wire you will use 'bacs'
- For Cheque you will use 'cheque'
- For Paypal you will use 'paypal'
- … / …


Similar answer:

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

    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;
        // get your payment method
        $chosen_gateway = WC()->session->chosen_payment_method;
        //echo $chosen_gateway;
        $fee = 5;
        if ( $chosen_gateway == 'cod' ) { //test with cash on delivery method
        WC()->cart->add_fee( 'delivery fee', $fee, false, '' );
    }


}

For anyone else looking to do this, I wanted to add a fee for Bank Transfers (BACS), here is the method I used:

//Hook the order creation since it is called during the checkout process:
add_filter('woocommerce_create_order', 'my_handle_bacs', 10, 2);

function my_handle_bacs($order_id, $checkout){
//Get the payment method from the $_POST
    $payment_method = isset( $_POST['payment_method'] ) ? wc_clean( $_POST['payment_method'] ) : '';

//Make sure it's the right payment method
    if($payment_method == "bacs"){

        //Use the cart API to add recalculate fees and totals, and hook the action to add our fee
        add_action('woocommerce_cart_calculate_fees', 'my_add_bacs_fee');
        WC()->cart->calculate_fees();
        WC()->cart->calculate_totals();
    }

    //This filter is for creating your own orders, we don't want to do that so return the $order_id untouched
    return $order_id;
}
function my_add_bacs_fee($cart){
    //Add the appropriate fee to the cart
    $cart->add_fee("Bank Transfer Fee", 40);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!