Anas
Anas

Reputation: 65

Show Cash on delivery (COD) based on specific cities in Woocommerce

In Woocommerce I am showing Cash on delivery payment method only for a particular city using the following code:

function payment_gateway_disable_city( $available_gateways ) {
    global $woocommerce;

    if ( isset( $available_gateways['cod'] ) && $woocommerce->customer->get_shipping_city() == 'New York') {
        unset( $available_gateways['cod'] );
    } 
    return $available_gateways;
}

add_filter( 'woocommerce_available_payment_gateways', 'payment_gateway_disable_city' );

It works fine. Now I need to handle multiple cities like Washington, San Francisco etc...

So I tried the following:

function payment_gateway_disable_city( $available_gateways ) {
    global $woocommerce;

    if ( isset( $available_gateways['cod'] ) && $woocommerce->customer->get_shipping_city() == 'New York', 'San Fransisco' ) {
        unset( $available_gateways['cod'] );
    } 
    return $available_gateways;
}

add_filter( 'woocommerce_available_payment_gateways', 'payment_gateway_disable_city' );

But it doesn't work… I get "WordPress experiencing technical difficulties".

Any help is appreciated.

Upvotes: 3

Views: 2292

Answers (1)

LoicTheAztec
LoicTheAztec

Reputation: 253784

Updated

The following code will enable COD payments for specific defined cities.

You need to use an array of allowed cities with in_array() PHP conditional function like:

add_filter( 'woocommerce_available_payment_gateways', 'cities_based_payment_gateway_cod' );
function cities_based_payment_gateway_cod( $available_gateways ) {
    if ( is_admin() ) return $available_gateways; // Only on frontend

    // HERE define the allowed cities in this array 
    $cities = array( 'New York', 'San Francisco' );

    if ( isset( $available_gateways['cod'] ) && ! in_array( WC()->customer->get_shipping_city(), $cities ) ) {
        unset( $available_gateways['cod'] );
    } 
    return $available_gateways;
}

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

Upvotes: 4

Related Questions