Show hide payment methods based on selected shipping method in Woocommerce

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:

enter image description here

Leave a Comment