Search code examples
phpwordpresswoocommerceshipping-methodpayment-method

Hide payment methods based on selected shipping method in WooCommerce


I was trying to hide two payment method if one shipping method selected by adding code below to theme function.php

// Filter payment gatways for different shipping methods
function my_custom_available_payment_gateways( $gateways ) {
    $chosen_shipping_rates = WC()->session->get( 'chosen_shipping_methods' );
    if ( in_array( 'flat_rate:7', $chosen_shipping_rates ) ) {
        unset( $gateways['stripe'] );
        unset( $gateways['ppec_paypal'] );
    }
    endif;
    return $gateways;
}
 add_filter( 'woocommerce_available_payment_gateways', 
'my_custom_available_payment_gateways' );

everything is working. except I got this error on product page.

Warning:
in_array() expects parameter 2 to be array, null given in [theme function.php and line number]


Solution

  • Use the following to prevent this error (also removed endif;):

    // Filter payment gatways for different shipping methods
    add_filter( 'woocommerce_available_payment_gateways', 'my_custom_available_payment_gateways', 10, 1 );
    function my_custom_available_payment_gateways( $available_gateways ) {
    if( is_admin() ) return $available_gateways; // Only for frontend
    
        $chosen_shipping_rates = (array) WC()->session->get( 'chosen_shipping_methods' );
    
        if ( in_array( 'flat_rate:12', $chosen_shipping_rates ) ) {
            unset( $available_gateways['stripe'], $available_gateways['ppec_paypal'] );
        }
    
        return $available_gateways;
    }
    

    Code goes in functions.php file of your active child theme (or active theme). It should works.