'Prevent guest users from ordering a product multiple times in WooCommerce

What I'm trying to do is utilize a code in my child theme's functions.php to block guests from ordering a specific product again. If they had a specific product_id in their cart (that they've ordered before), they would be redirected to a specific url instead of the order being completed.

Our website uses phone number (without a zero in the first digit) as username and to make the order process as simple as possible, the user is not required to login during checkout.

We're trying to find a way to check if the billing_phone is an existing username, then checking if the user_id have bought specific product(s) before. If they did, trying to prevent that and redirect them to specific url, after they click place order button on checkout page.


Inspired by:

We tried to construct this piece of code, but without success. The order was not prevented from repeating:

function action_woocommerce_check_cart_items() {
    
  // Retrieve the current user from billing_phone
    
      // get all the order data
      $order = new WC_Order($order_id);
  
      //get the user phone from the order
      $order_phone = $order->billing_phone;
  
      //phone without zero in first digit
      $phone_nozero = substr($order_phone, 1);
      
      //gets user_id using phone number and saves it to $current_user
      $current_user = get_user_by('login', $phone_nozero);
    
    
    // Initialize
    $flag = false;
    
    // Loop through cart items
    foreach( WC()->cart->get_cart() as $cart_item ) {

        $product_id = "916";

        // Checks if a user (by email or ID or both) has bought an item
        if ( wc_customer_bought_product( $current_user->user_email, $current_user->ID, $product_id ) ) {
            // Flag becomes true
            $flag = true;
            
            // Break loop
            break;
        }
    }
    
    // True
    if ( $flag ) {
//Here, we likely require a code to prevent the order from being completed.

//redirect to specific url

        wp_redirect( 'https://myspecificurl.com' );
    }
}  

//hook for after clicking place order button. inspired by : 

add_action( 'woocommerce_new_order' , 'action_woocommerce_check_cart_items', 1, 1 );

Any suggestions would be greatly appreciated.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source