Skip to content
  1. Home
  2. Blog

how-to · · 9 min read

how to limit woocommerce purchases per customer per day, week or month

Cap how many of a product one customer can buy per day, week or month in WooCommerce: guests matched by email, classic and block checkout, full code.

By Big Bad Agency

“Two per customer per week.” It’s how you run a limited drop, keep a loss-leader from being bought up by one reseller, or stop one person clearing out a restock in the first ten minutes.

WooCommerce can’t do it out of the box. The closest thing in core is Sold individually on the product’s Inventory tab, which WooCommerce describes as “Limit purchases to 1 item per order”. That’s one per order. The same person can place five orders in a row and get five. Nothing in core remembers what a customer bought last week.

Here’s the code that does: one function to set the limits, three hooks to enforce them, and the two places most purchase-limit snippets leak.

first, decide what one customer is

A limit is only as good as your answer to “is this the same person?” There are two handles:

  • The account. Easy if everyone logs in. Most stores allow guest checkout, so on its own this misses everyone who doesn’t.
  • The billing email. Works for guests, and it’s what WooCommerce’s own Analytics uses to tie a guest order to a customer. Someone determined can use a second email, and a typo makes a new person.

We use both: an order counts against you if it’s on your account or carries your billing email. That closes the easy gap (log out, check out as a guest) without pretending to stop someone with ten email addresses. If you need that, you need identity checks, not a snippet.

The new vs returning customers post goes through the same choice for reporting, and why it changes the answer.

the other decisions

  • Which orders count. We count processing, completed and on-hold. On-hold covers bank transfers and cheques that haven’t cleared: the customer has committed, so letting them order again before it clears would get round the limit. Pending, failed, cancelled and refunded orders don’t count.
  • What a period is. We use calendar periods in your site’s time zone: today since midnight, this week since your Week Starts On setting (Settings → General), this month since the 1st. “Two per week” then resets on Monday morning, which is easy to explain on a product page. A rolling window (“two in any 7 days”) is fairer to someone who bought on Sunday, but harder to say out loud.
  • Variations. A limit set on a variable product covers every size together. Two of the small plus one of the large is three.

1. set the limits

Paste the code into a small plugin or your child theme’s functions.php. The whole thing, as one file, is at the end.

function bb_purchase_limit_rules() {
	return array(
		123 => array(
			'max'    => 2,
			'period' => 'week',
		),
	);
}

The key is the product ID (on the product’s edit screen, it’s the number in the URL after post=). max is the most one customer can buy in the period. period is day, week or month. Add a line per limited product.

2. work out when the period started

function bb_purchase_limit_period_start( $period ) {
	$now = new DateTimeImmutable( 'now', wp_timezone() );

	switch ( $period ) {
		case 'day':
			$start = $now->setTime( 0, 0 );
			break;
		case 'week':
			$week_starts = (int) get_option( 'start_of_week', 1 ); // 0 = Sunday, 1 = Monday.
			$days_back   = ( (int) $now->format( 'w' ) - $week_starts + 7 ) % 7;
			$start       = $now->setTime( 0, 0 )->modify( "-{$days_back} days" );
			break;
		case 'month':
			$start = $now->modify( 'first day of this month' )->setTime( 0, 0 );
			break;
		default:
			return null;
	}

	return $start->getTimestamp();
}

wp_timezone() is the time zone in Settings → General. Skip it and “today” starts at midnight UTC, which for a store in North America is late afternoon or evening the day before. An unknown period returns null, and the limit is skipped rather than guessed.

3. count what they already bought

function bb_purchase_limit_already_bought( $product_id, $since, $customer_id, $email ) {
	$who = array();
	if ( $customer_id ) {
		$who[] = (int) $customer_id;
	}
	if ( $email && is_email( $email ) ) {
		$who[] = $email;
	}
	if ( ! $who ) {
		return 0;
	}

	$orders = wc_get_orders(
		array(
			'customer'     => $who,
			'status'       => array( 'wc-processing', 'wc-completed', 'wc-on-hold' ),
			'date_created' => '>=' . $since,
			'limit'        => -1,
		)
	);

	$bought = 0;
	foreach ( $orders as $order ) {
		foreach ( $order->get_items() as $item ) {
			// For a variation, get_product_id() is the parent, so a limit covers every size.
			if ( (int) $item->get_product_id() === (int) $product_id ) {
				$bought += (int) $item->get_quantity();
			}
		}
	}

	return $bought;
}

Passing an ID and an email to customer matches orders with either one. We checked that in WooCommerce’s source for both order storage types: the older posts table and the newer High-Performance Order Storage (HPOS). Both treat the list as “or”. wc_get_orders works the same on either, so this needs no change if you switch storage later.

4. turn quantities into messages

function bb_purchase_limit_cart_quantities() {
	$quantities = array();
	if ( ! WC()->cart ) {
		return $quantities;
	}
	foreach ( WC()->cart->get_cart() as $cart_item ) {
		$id                = (int) $cart_item['product_id'];
		$quantities[ $id ] = ( $quantities[ $id ] ?? 0 ) + (int) $cart_item['quantity'];
	}
	return $quantities;
}

function bb_purchase_limit_errors( $quantities, $customer_id, $email ) {
	$errors = array();

	foreach ( bb_purchase_limit_rules() as $product_id => $rule ) {
		if ( empty( $quantities[ $product_id ] ) ) {
			continue;
		}
		$since = bb_purchase_limit_period_start( $rule['period'] );
		if ( null === $since ) {
			continue;
		}

		$bought = bb_purchase_limit_already_bought( $product_id, $since, $customer_id, $email );
		$left   = max( 0, (int) $rule['max'] - $bought );

		if ( $quantities[ $product_id ] > $left ) {
			$errors[] = sprintf(
				__( 'You can buy %1$d of %2$s per %3$s. You have %4$d left this %3$s.', 'bb-purchase-limits' ),
				(int) $rule['max'],
				get_the_title( $product_id ),
				$rule['period'],
				$left
			);
		}
	}

	return $errors;
}

The message says how many are left, not just “limit reached”. Someone with one left can fix their cart. Someone told only “no” usually emails you.

5. enforce it in three places

This is where most snippets leak. A store has several ways in, and a check on only one of them is a check on nobody.

When they add to the cart. The early, friendly check:

add_filter(
	'woocommerce_add_to_cart_validation',
	function ( $passed, $product_id, $quantity ) {
		$product_id = (int) $product_id;
		if ( ! $passed || ! isset( bb_purchase_limit_rules()[ $product_id ] ) ) {
			return $passed;
		}

		$in_cart = bb_purchase_limit_cart_quantities();
		$total   = ( $in_cart[ $product_id ] ?? 0 ) + (int) $quantity;
		$email   = WC()->customer ? WC()->customer->get_billing_email() : '';
		$errors  = bb_purchase_limit_errors( array( $product_id => $total ), get_current_user_id(), $email );

		foreach ( $errors as $message ) {
			wc_add_notice( $message, 'error' );
		}
		return empty( $errors );
	},
	10,
	3
);

WooCommerce calls this filter from the normal add-to-cart form, the AJAX button on shop pages, and the Store API that the cart and product blocks use. For a variation, the form and the Store API pass the parent product, so it’s checked against its product’s limit. It adds what’s already in the cart, so “add one, then add one more” can’t sneak past. Anything this early check misses, the next one catches.

On the cart and at checkout. The check that can’t be skipped:

add_action(
	'woocommerce_check_cart_items',
	function () {
		$email = WC()->customer ? WC()->customer->get_billing_email() : '';
		foreach ( bb_purchase_limit_errors( bb_purchase_limit_cart_quantities(), get_current_user_id(), $email ) as $message ) {
			wc_add_notice( $message, 'error' );
		}
	}
);

Quantities can be changed on the cart page after adding, so the add-to-cart check isn’t enough. woocommerce_check_cart_items runs on the cart page, on the classic checkout page, again when the classic checkout is submitted, and inside the Store API’s own cart check. On the classic checkout it runs after WooCommerce saves the email from the form, so a guest is caught by the email they just typed. Any error notice stops the order.

For guests on the checkout block. The one almost every snippet misses:

add_action(
	'woocommerce_store_api_checkout_update_order_from_request',
	function ( $order ) {
		$errors = bb_purchase_limit_errors(
			bb_purchase_limit_cart_quantities(),
			$order->get_customer_id(),
			$order->get_billing_email()
		);
		if ( $errors ) {
			throw new \Automattic\WooCommerce\StoreApi\Exceptions\RouteException(
				'bb_purchase_limit',
				implode( ' ', $errors ),
				400
			);
		}
	}
);

The checkout block checks the cart before it saves the email typed into the form. A guest whose email isn’t in the session yet passes that check as “nobody”. This hook runs later, once the order carries the billing email. Throwing a RouteException there stops the checkout and shows the message. The hooks classic-checkout snippets usually rely on, woocommerce_checkout_process and woocommerce_after_checkout_validation, never run on the block checkout at all, which is why those snippets let block-checkout guests through.

before it goes live

  • Test every way in, on staging. Logged in and as a guest. Classic checkout and the checkout block if you use both. Add over the limit from the product page and from a shop-page button. Change the quantity on the cart page. Then place an order at the limit and try once more.
  • A guest’s first refusal comes at checkout. We can’t know who a guest is until they type an email, so they find out on the checkout page, not the product page. Saying the limit on the product page (“2 per customer per week”) stops it being a surprise.
  • Refunds. A fully refunded order stops counting. A partial refund doesn’t change the count: someone who bought two and had one refunded has still used two.
  • Busy products. Each check runs one order query per limited product in the cart. That’s fine for a handful of limited products. A rule on every product in a large store wants a cached count per customer instead.
  • Mind your text domain. Replace bb-purchase-limits with your plugin’s or theme’s.

when to use a plugin instead

This covers a fixed list of products with one limit each. If staff need to set limits in the product screen, limits by role or category, or limits on order value, use a dedicated purchase-limit plugin.

If you’re running a drop next week and need “two per person per week” to actually hold, this is the whole job, in code you own.

the full file

Save it as wp-content/plugins/purchase-limits/purchase-limits.php, change the product ID in bb_purchase_limit_rules(), and activate it under Plugins:

<?php
/**
 * Plugin Name: Purchase Limits per Period
 * Description: Limit how many of a product one customer can buy per day, week or month.
 * Version:     1.0.0
 */

defined( 'ABSPATH' ) || exit;

function bb_purchase_limit_rules() {
	return array(
		123 => array(
			'max'    => 2,
			'period' => 'week',
		),
	);
}

function bb_purchase_limit_period_start( $period ) {
	$now = new DateTimeImmutable( 'now', wp_timezone() );

	switch ( $period ) {
		case 'day':
			$start = $now->setTime( 0, 0 );
			break;
		case 'week':
			$week_starts = (int) get_option( 'start_of_week', 1 );
			$days_back   = ( (int) $now->format( 'w' ) - $week_starts + 7 ) % 7;
			$start       = $now->setTime( 0, 0 )->modify( "-{$days_back} days" );
			break;
		case 'month':
			$start = $now->modify( 'first day of this month' )->setTime( 0, 0 );
			break;
		default:
			return null;
	}

	return $start->getTimestamp();
}

function bb_purchase_limit_already_bought( $product_id, $since, $customer_id, $email ) {
	$who = array();
	if ( $customer_id ) {
		$who[] = (int) $customer_id;
	}
	if ( $email && is_email( $email ) ) {
		$who[] = $email;
	}
	if ( ! $who ) {
		return 0;
	}

	$orders = wc_get_orders(
		array(
			'customer'     => $who,
			'status'       => array( 'wc-processing', 'wc-completed', 'wc-on-hold' ),
			'date_created' => '>=' . $since,
			'limit'        => -1,
		)
	);

	$bought = 0;
	foreach ( $orders as $order ) {
		foreach ( $order->get_items() as $item ) {
			if ( (int) $item->get_product_id() === (int) $product_id ) {
				$bought += (int) $item->get_quantity();
			}
		}
	}

	return $bought;
}

function bb_purchase_limit_cart_quantities() {
	$quantities = array();
	if ( ! WC()->cart ) {
		return $quantities;
	}
	foreach ( WC()->cart->get_cart() as $cart_item ) {
		$id                = (int) $cart_item['product_id'];
		$quantities[ $id ] = ( $quantities[ $id ] ?? 0 ) + (int) $cart_item['quantity'];
	}
	return $quantities;
}

function bb_purchase_limit_errors( $quantities, $customer_id, $email ) {
	$errors = array();

	foreach ( bb_purchase_limit_rules() as $product_id => $rule ) {
		if ( empty( $quantities[ $product_id ] ) ) {
			continue;
		}
		$since = bb_purchase_limit_period_start( $rule['period'] );
		if ( null === $since ) {
			continue;
		}

		$bought = bb_purchase_limit_already_bought( $product_id, $since, $customer_id, $email );
		$left   = max( 0, (int) $rule['max'] - $bought );

		if ( $quantities[ $product_id ] > $left ) {
			$errors[] = sprintf(
				__( 'You can buy %1$d of %2$s per %3$s. You have %4$d left this %3$s.', 'bb-purchase-limits' ),
				(int) $rule['max'],
				get_the_title( $product_id ),
				$rule['period'],
				$left
			);
		}
	}

	return $errors;
}

add_filter(
	'woocommerce_add_to_cart_validation',
	function ( $passed, $product_id, $quantity ) {
		$product_id = (int) $product_id;
		if ( ! $passed || ! isset( bb_purchase_limit_rules()[ $product_id ] ) ) {
			return $passed;
		}

		$in_cart = bb_purchase_limit_cart_quantities();
		$total   = ( $in_cart[ $product_id ] ?? 0 ) + (int) $quantity;
		$email   = WC()->customer ? WC()->customer->get_billing_email() : '';
		$errors  = bb_purchase_limit_errors( array( $product_id => $total ), get_current_user_id(), $email );

		foreach ( $errors as $message ) {
			wc_add_notice( $message, 'error' );
		}
		return empty( $errors );
	},
	10,
	3
);

add_action(
	'woocommerce_check_cart_items',
	function () {
		$email = WC()->customer ? WC()->customer->get_billing_email() : '';
		foreach ( bb_purchase_limit_errors( bb_purchase_limit_cart_quantities(), get_current_user_id(), $email ) as $message ) {
			wc_add_notice( $message, 'error' );
		}
	}
);

add_action(
	'woocommerce_store_api_checkout_update_order_from_request',
	function ( $order ) {
		$errors = bb_purchase_limit_errors(
			bb_purchase_limit_cart_quantities(),
			$order->get_customer_id(),
			$order->get_billing_email()
		);
		if ( $errors ) {
			throw new \Automattic\WooCommerce\StoreApi\Exceptions\RouteException(
				'bb_purchase_limit',
				implode( ' ', $errors ),
				400
			);
		}
	}
);

We checked every hook here against the WooCommerce 10.7 source, and tested the period and counting logic against stubbed WordPress functions. We haven’t run it on your store. Staging first.

Disagree? Good.

Write to a person: hello@bigbad.agency. We answer within a business day.

Start a project