0

I need to disable free shipping if the chosen payment method is cash on delivery. I found a possible solution in this post but it don't completely works. This is the code i used:

add_action( 'woocommerce_package_rates','show_hide_shipping_methods', 10, 2 );
function show_hide_shipping_methods( $rates, $package ) {
    // HERE Define your targeted shipping method ID
    $payment_method        = 'cod';

    $chosen_payment_method = WC()->session->get('chosen_payment_method');

    if( $payment_method == $chosen_payment_method ){
        unset($rates['free_shipping:2']);
    }
    return $rates;
}

add_action( 'woocommerce_review_order_before_payment', 'payment_methods_trigger_update_checkout' );
function payment_methods_trigger_update_checkout(){
    // jQuery code
    ?>
    <script type="text/javascript">
        (function(jQuery){
            jQuery( 'form.checkout' ).on( 'change blur', 'input[name^="payment_method"]', function() {
                setTimeout(function(){
                    jQuery(document.body).trigger('update_checkout');
                }, 250 );
            });
        })(jQuery);
    </script>
    <?php
}

add_action( 'woocommerce_checkout_update_order_review', 'refresh_shipping_methods' );
function refresh_shipping_methods( $post_data ){
    // HERE Define your targeted shipping method ID
    $payment_method = 'cod';
    $bool           = true;

    if ( WC()->session->get('chosen_payment_method') === $payment_method )
        $bool = false;

    // Mandatory to make it work with shipping methods
    foreach ( WC()->cart->get_shipping_packages() as $package_key => $package ){
        WC()->session->set( 'shipping_for_package_' . $package_key, $bool );
    }
    WC()->cart->calculate_shipping();
}

This code hide the free shipping method not only when i check the cash on delivery payment, but it seems to do it in random mode.

0 Answers0