hooks – woocommerce_add_to_cart_validation max quantity depending on user geoip

Question

I have this hook working for all customers, which only allows 3 itens in cart. This is working because we always send 3 samples in a box and always to Portugal.
But now we have to send to France and we need to reinforce the box with more plastic, and as consequence reduce the allowed itens in the cart for 2 samples only.

How to add a condition based on geoip?

    // Checking and validating when products are added to cart
add_filter( 'woocommerce_add_to_cart_validation', 'only_three_items_allowed_add_to_cart', 10, 3 );

function only_three_items_allowed_add_to_cart( $passed, $product_id, $quantity ) {

    $cart_items_count = WC()->cart->get_cart_contents_count();
    $total_count = $cart_items_count + $quantity;
    $userInfo = geoip_detect2_get_info_from_current_ip();
            if ( $userInfo->country->isoCode == "PT")  {
                // set max qty to 3 else max qty to 2
            }
            

    if( $cart_items_count >= 3 || $total_count > 3 ){
        // Set to false
        $passed = false;
        // Display a message
      

        wc_add_notice( __( "Error, more than 3 itens.", "sage" ), "error" );

         $message =  sprintf(  __( "Error, more than 3 itens.", "sage" ), "error"  );

         $data = array(
           'error' => true,
           'description' =>  $message ,
           );           

        echo wp_send_json($data);


    }
    return $passed;
}

0
Romeu Costa 1 month 2023-04-19T12:32:16-05:00 0 Answers 0 views 0

Leave an answer

Browse
Browse