title: Only allow a customer to buy a certain product once, even if they aren't logged in
body: <p>I'm trying to stop customers buying a certain product more than once, even if they aren't logged in. </p>
  
  <p>I've tried a few different functions. </p>
  
  <pre><code>&lt;?php 
      add_action('woocommerce_after_checkout_validation',    custom_after_checkout_validation');
  
      function custom_after_checkout_validation( $posted ) {
      $address = $order-&gt;get_billing_address_1();
      $email = $order-&gt;get_billing_email();
      // Set HERE ine the array your specific target product IDs
      $prod_arr = array( '19861', '19908' );
  
      // Get all customer orders
      $customer_orders = get_posts( array(
          'numberposts' =&gt; -1,
          'meta_key'    =&gt; '_billing_email',
          'meta_value'  =&gt; $email,
          'post_type'   =&gt; 'shop_order', // WC orders post type
          'post_status' =&gt; 'wc-completed' // Only orders with status    "completed"
         ) );
          foreach ( $customer_orders as $customer_order ) {
          // Updated compatibility with WooCommerce 3+
          //$order_id = method_exists( $order, 'get_id' ) ? $order-&gt;get_id()   : $order-&gt;id;----------------
          $orders = wc_get_order( $customer_order );
          foreach ($orders as $order2) {
              $address2 = $order-&gt;get_billing_address_1();
  
              foreach($order2-&gt;get_items() as $item){
                  // WC 3+ compatibility
                  if ( version_compare( WC_VERSION, '3.0', '&lt;' ) ) {
                      $product_id = $item['product_id'];
                  }
                  else {
                      $product_id = $item-&gt;get_product_id();
                  }
  
                  // Your condition related to your 2 specific products Ids
                  if ( in_array( $product_id, $prod_arr ) ) {
                      if ($address == $address2) {
                          wc_add_notice( __( "You have already purchased    this product.", 'woocommerce' ), 'error' );
                      }
                  }
              }
             }
          }
        }
  ?&gt;
  </code></pre>
  
  <p>This one is returning an internal server error. Please Help! TIA</p>