How to prevent a user for purchasing multiple times a given product

Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedInPrint this page

In certain scenarios, the products and their attached licenses are required to be sold just once to each individual customer. Once purchased if try later to buy the same product it should block the add-to-cart operation.

This can be achieved programmatically through a custom code. That works for any product type as physical, virtual, downloadable, simple, variation etc. There isn’t a specific requirement on the product or the license set-up, for the functionality to work.

The following sample code should be inserted within a custom file on /wp-content/mu-plugins/ folder. Within the same, the variable $check_for_product_ids contains the products that are required to be purchased just once.

    add_filter ( 'woocommerce_add_to_cart_validation', '__woocommerce_add_to_cart_validation', 99, 3 );
    function __woocommerce_add_to_cart_validation( $status, $product_id, $quantity )
            if ( is_user_logged_in() ===    FALSE )
                return FALSE;
            //rtrieve all previous orders for the current user
            $args = array(
                            'customer_id'   => get_current_user_id(),
                            'limit'         => -1, // to retrieve _all_ orders by this user
            $orders = wc_get_orders($args);
            $found_product  =   FALSE;
            $check_for_product_ids  =   array( 1, 10, 194 );
            foreach ( $orders   as $order )
                    foreach ( $order->get_items() as $item_id => $item ) 
                            if ( in_array ( $item->get_product_id(), $check_for_product_ids )   &&  $product_id ==  $item->get_product_id() )
                                    $found_product  =   TRUE;
                                    break 2;
            if ( ! $found_product )
                return $status;
            wc_add_notice ('Product already purchased', 'error');
            return FALSE;   


By woocommerce-sl, posted on September 22, 2022

Notify of
Inline Feedbacks
View all comments