-1

At checkout I need to block delivery in certain cities for a specific product (not all products). When user fills in a city that should be blocked based on a list that I defined, the checkout process blocks the order and a custom notice error appear perfectly as desired.

I use this code to block delivery in certain city:

add_action( 'woocommerce_checkout_process', 'shipping_validate_city' );
function shipping_validate_city() {
    if ( in_array( $product_id, array( 3059, 3058) ) ) {
        $disableCityList = array (
            'Rabat',
            'Temara',
            'Sale',
            'Tamessna',
        );
        $billingCity = isset( $_POST['billing_city'] ) ? trim( $_POST['billing_city'] ) : '';
        $billingCity = str_replace(array('-','_'),' ',$billingCity);
        $billingCity = ucwords($billingCity);

        if (in_array($billingCity, $disableCityList))
        {
            wc_add_notice( __('this product not allowed shipping for the city you mentioned') , 'error' );
        }
    }
}

My problem is. How can I do this for specific product only?

Ondrej K.
  • 8,841
  • 11
  • 24
  • 39
A.hmimou
  • 5
  • 1
  • 5

1 Answers1

0

I think it work now, i fetch product id from cart items

foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
    $pdt_id = $cart_item['product_id'];
}

and i used to check if the product exist in array,

add_action( 'woocommerce_checkout_process', 'shipping_validate_city' );

function shipping_validate_city() {
$pdt_id= array();
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
    $pdt_id = $cart_item['product_id'];
}
if ( in_array( $pdt_id , array( 3059, 3058) ) ) {
    $enableCityList = array (
    'Rabat',
    'Temara',
    'Sale',
    'Tamessna',
    'Tamesna',
    'RABAT',
    'TEMARA',
    'SALE',
    'TAMESSNA',
    'TAMESNA',
    'Salé',
    );
    $billingCity = isset( $_POST['billing_city'] ) ? trim( $_POST['billing_city'] ) : '';
    $billingCity = str_replace(array('-','_'),' ',$billingCity);
    $billingCity = ucwords($billingCity);

    if (!in_array($billingCity, $enableCityList))
    {
    wc_add_notice( __('Livraison à ville que vous avez indiquée non couverts pour ce produit ') , 'error' );
    }
}

}

A.hmimou
  • 5
  • 1
  • 5