Jawad Ahmad
Jawad Ahmad

Reputation: 49

Disable Cash On Delivery for specific states and cities

I am trying to disable Cash On delivery method for specific cities and states but there is some issue and when I put this code, the add to cart waiting circle keeps circulating.

function payment_gateway_disable_country( $available_gateways ) {
    global $woocommerce;
    $targeted_states = array('PB','IS','GB', 'KP');
    //$targeted_states = array('PB','IS');
    $user_state = $woocommerce->customer->get_billing_state();
    if ( is_admin() ) return;

    if (in_array($user_state, $targeted_states)) {
        
        return $available_gateways;
    }
  
    if ( ($woocommerce->customer->get_billing_city() == "LAHORE") ||
    ($woocommerce->customer->get_billing_city() == "lahore") ||
    ($woocommerce->customer->get_billing_city() == "Lahore") ||
    ($woocommerce->customer->get_billing_city() == "lhr") ||
    ($woocommerce->customer->get_billing_city() == "islamabad") ||
    ($woocommerce->customer->get_billing_city() == "Islamabad") ||
    ($woocommerce->customer->get_billing_city() == "isl") ||
    ($woocommerce->customer->get_billing_city() == "ISLAMABAD") ||
    ($woocommerce->customer->get_billing_city() == "rawalpindi") ||
    ($woocommerce->customer->get_billing_city() == "rwp") ||
    ($woocommerce->customer->get_billing_city() == "Rawalpindi") ||
    ($woocommerce->customer->get_billing_city() == "RAWALPINDI")) {
        
        return $available_gateways;
    } 
    else {
        unset( $available_gateways['cod']);
    }
    return $available_gateways;
}
add_filter( 'woocommerce_available_payment_gateways', 'payment_gateway_disable_country' );

Upvotes: 1

Views: 150

Answers (1)

Vincenzo Di Gaetano
Vincenzo Di Gaetano

Reputation: 4100

There are some errors in your function. Are you sure you want to check state instead of country ("PB", "IS", "GB", "KP")?

You can optimize your function like this:

add_filter( 'woocommerce_available_payment_gateways', 'payment_gateway_disable_country' );
function payment_gateway_disable_country( $available_gateways ) {

    if ( is_admin() ) {
        return $available_gateways;
    }

    if ( ! isset( $available_gateways['cod'] ) ) {
        return $available_gateways;
    }

    global $woocommerce;
    $targeted_countries = array( 'PB','IS','GB', 'KP' );
    $targeted_cities    = array( 'LAHORE', 'lahore', 'Lahore', 'lhr', 'islamabad', 'Islamabad', 'isl', 'ISLAMABAD', 'rawalpindi', 'rwp', 'Rawalpindi', 'RAWALPINDI' );
    
    if ( in_array( $woocommerce->customer->get_billing_country(), $targeted_countries ) ) {
        unset( $available_gateways['cod'] );
    }
  
    if ( in_array( $woocommerce->customer->get_billing_city(), $targeted_cities ) ) {
        unset( $available_gateways['cod'] );
    }

    return $available_gateways;
}

The code has been tested and works. Add it in your active theme's functions.php.

Upvotes: 2

Related Questions