Disable shipping method based on chosen payment method in Woocommerce

后端 未结 1 411
星月不相逢
星月不相逢 2020-12-11 22:38

I need to disable specific shipping method if user selected payment \"Cash on Delivery\". The problem is that the following code works only if I reset WooCommerce transient

相关标签:
1条回答
  • 2020-12-11 22:52

    Updated on March 2019

    Here is the complete working way to make "COD" payment method disable a specific shipping method.

    You will have to set in the first function the shipping method Id that you wish to hide.

    The code:

    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['flat_rate:12']);
        }
        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($){
                $( 'form.checkout' ).on( 'change blur', 'input[name^="payment_method"]', function() {
                    setTimeout(function(){
                        $(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();
    }
    

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

    To be able to get the correct shipping method ID you can use your browser inspector, this way:

    You may need to empty cart before testing this code.

    0 讨论(0)
提交回复
热议问题