Advertisement
nshelper

Untitled

Sep 12th, 2022
131
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.63 KB | None | 0 0
  1.     //prevent the logged-in user to purchase twice the same product
  2.     add_filter ( 'woocommerce_add_to_cart_validation', '__woocommerce_add_to_cart_validation', 99, 3 );
  3.     function __woocommerce_add_to_cart_validation( $status, $product_id, $quantity )
  4.         {
  5.             if ( is_user_logged_in() ===    FALSE )
  6.                 return FALSE;
  7.                
  8.             //rtrieve all previous orders for the current user
  9.             $args = array(
  10.                             'customer_id'   => get_current_user_id(),
  11.                             'limit'         => -1, // to retrieve _all_ orders by this user
  12.                         );
  13.             $orders = wc_get_orders($args);
  14.            
  15.             $found_product  =   FALSE;
  16.             $check_for_product_ids  =   array( 1, 10, 194 );
  17.            
  18.             foreach ( $orders   as $order )
  19.                 {
  20.                     foreach ( $order->get_items() as $item_id => $item )
  21.                         {
  22.                             if ( in_array ( $item->get_product_id(), $check_for_product_ids )   &&  $product_id ==  $item->get_product_id() )
  23.                                 {
  24.                                     $found_product  =   TRUE;
  25.                                     break 2;
  26.                                 }
  27.                         }
  28.                 }
  29.                
  30.             if ( ! $found_product )
  31.                 return $status;
  32.            
  33.             //wc_add_to_cart_message( array( $product_id => $quantity ), true );  
  34.             wc_add_notice ('Product already purchased', 'error');
  35.            
  36.             return FALSE;  
  37.         }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement