Categories
CMS Development Wordpress

Add extra cost to shipping method itself in woocommerce

I found the following code from this link:
https://stackoverflow.com/questions/52138784/add-a-fee-based-on-shipping-method-and-payment-method-in-woocommerce

The code works great if you want to add an extra fee if the “cash on delivery” payment method selected.

My question is how to add the extra cost to the shipping method itself when “cash on delivery” method is selected, not show it as another field with extra cost.

the code:

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

        ## ------ Your Settings (below) ------ ##
        $your_payment_id      = 'cod'; // The payment method
        $your_shipping_method = 'some_custom_shipping_method_id'; // The shipping method
        $fee_amount           = 12; // The fee amount
        ## ----------------------------------- ##

        $chosen_payment_method_id  = WC()->session->get( 'chosen_payment_method' );
        $chosen_shipping_method_id = WC()->session->get( 'chosen_shipping_methods' )[0];
        $chosen_shipping_method    = explode( ':', $chosen_shipping_method_id )[0];

        if ( $chosen_shipping_method == $your_shipping_method 
        && $chosen_payment_method_id == $your_payment_id ) {
            $fee_text = __( "Extra ".$chosen_shipping_method );
            $cart->add_fee( $fee_text, $fee_amount, false );
        }
    }

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

Leave a Reply

Your email address will not be published. Required fields are marked *