DEV Community

Muhammad Shoaib
Muhammad Shoaib

Posted on

Prevent Repeat Purchase (WooCommerce)

Depending on what kind of products you sell, you may want to prevent customers from purchasing a WooCommerce product more than once from your store. For some shops, you may want to disable any repeat purchases at all, or you may want to prevent repeat purchase only for a specific product.

Prevent Repeat Purchase with WooCommerce: Specific Product

The first thing we’ll need to do (and the one essential thing) is to prevent repeat purchases — this is where we’ll check that the customer has already bought the product, and ensure it can’t be purchased if so. We’ll only need the ID of the product that should not be purchased again.

//Hook into the after checkout validation action, add a callback function named 'validate_no_repeat_purchase' with a priority of 10 and pass two arguments.
add_action( 'woocommerce_after_checkout_validation', 'validate_no_repeat_purchase', 10, 2 );

//The callback function accepts the array of posted checkout data and an array of errors
function validate_no_repeat_purchase( $data, $errors ) {
    //extract the posted 'billing_phone' and use that as an argument for querying orders.
    $args = array(
        'billing_phone' => (string) $data['billing_phone'],
        'date_created' => '>' . ( time() - 60*60*24*7 )
    $match = 0;

    //loop through the cart items to see if one is the product that doesn't allow repeat purchases.
    foreach( WC()->cart->get_cart() as $cart_item ) {
        $product_id_no_repeat_purchases = array(34855, 34854, 34841);//substitute your product id.
    if (in_array($cart_item['product_id'], $    )) {
                //use the WooCommerce helper function to query for orders with this phone number:
                $orders = wc_get_orders( $args );
                foreach ($orders as $order) {
                    foreach ( $order->get_items() as $item_id => $item ) {
                    $product_id = $item->get_product_id();
                        if($product_id == $cart_item['product_id']) {
                            $match = 1;
    //if an order with this email exists, don't allow another one.
    if ( $match == 1) {
        $errors->add( 'validation', 'Repeat orders are not allowed.' );

And if you want to vallidate by email just change the $args = array('customer' => $data['billing_email'],);

Discussion (1)

sdeiss1977 profile image

How can I check if the payment details the user enters have already been entered before? Situation: A user may register with a different email address in order to be able to buy a product again he shouldn't be allowed to repurchase. This should be prevented by not only checking the email address, but also the payment details, e.g. credit card number.