phpwordpresswoocommercepayment-method

Hide WooCommerce payment methods for specific shipping zones and min subtotal


In WooCommerce, I'm trying to remove "Cash on delivery" payment method when cart subtotal is up to $250 for specific shipping zones names (Zone 1, Zone 4 and Zone 7).

All others zones must not have this restriction.

Here is my incomplete code based on this thread:

add_filter( 'woocommerce_available_payment_gateways', 'change_payment_gateway', 20, 1);
function change_payment_gateway( $gateways ){
    
    $zone = $shipping_zone->get_zone_name();

    if( WC()->cart->subtotal > 250 ) && if($zone=='Zone 1','Zone 4','Zone 7'){
    
        unset( $gateways['cod'] );
    }
    return $gateways;
}

Any help is appreciated.


Solution

  • The following will remove "Cash on delivery" payment gateway for specific shipping zones and when cart subtotal is up to 250:

    add_filter( 'woocommerce_available_payment_gateways', 'conditionally_remove_payment_methods', 20, 1);
    function conditionally_remove_payment_methods( $gateways ){
        // Not in backend (admin)
        if( is_admin() ) 
            return $gateways;
    
        // HERE below your targeted zone names
        $targeted_zones_names = array('Zone 1','Zone 4','Zone 7');
    
        $chosen_methods    = WC()->session->get( 'chosen_shipping_methods' ); // The chosen shipping mehod
        $chosen_method     = explode(':', reset($chosen_methods) );
        $shipping_zone     = WC_Shipping_Zones::get_zone_by( 'instance_id', $chosen_method[1] );
        $current_zone_name = $shipping_zone->get_zone_name();
    
        if( WC()->cart->subtotal > 250 && in_array( $current_zone_name, $targeted_zones_names ) ){
            unset( $gateways['cod'] );
        }
        return $gateways;
    }
    

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