Show hide payment methods based on selected shipping method in Woocommerce

后端 未结 1 1091
时光说笑
时光说笑 2020-12-12 05:13

I would like to hide some payment method and enable another one when I select a specified “Shipping Method\" in flexible Shipping plugin form wpdesk.

I have already

相关标签:
1条回答
  • 2020-12-12 06:05

    The following code example will enable / disable payment gateways based on chosen shipping method.

    In this example, we have 3 shipping methods and 3 payment gateways. Each selected shipping method will enable only one different payment gateway.

    add_filter( 'woocommerce_available_payment_gateways', 'payment_gateways_based_on_chosen_shipping_method' );
    function payment_gateways_based_on_chosen_shipping_method( $available_gateways ) {
        // Not in backend (admin) and Not in order pay page
        if( is_admin() ||  is_wc_endpoint_url('order-pay') ) 
            return $available_gateways;
         
        // Get chosen shipping methods
        $chosen_shipping_methods = (array) WC()->session->get( 'chosen_shipping_methods' );
    
        if ( in_array( 'flat_rate:12', $chosen_shipping_methods ) )
        {
            unset( $gateways['bacs'] );
            unset( $gateways['cod'] );
        }
        elseif ( in_array( 'flat_rate:14', $chosen_shipping_methods ) )
        {
            unset( $gateways['bacs'] );
            unset( $gateways['paypal'] );
        }
        elseif ( in_array( 'free_shipping:10', $chosen_shipping_methods ) )
        {
            unset( $gateways['cod'] );
            unset( $gateways['paypal'] );
        }
    
        return $gateways;
    }
    

    Code goes in functions.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:

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