Yes, “manage stock” is a nice feature to make sure you don’t oversell a given product based on the stock you have in your warehouse. However, what if you also need to have a “daily sales limit” – say you can’t sell more than 3 of a given product ID in a given day?
This is an interesting functionality that is also helpful for you to learn how to get today’s orders, how to loop through the orders to find a specific product ID and sum its quantities, and finally how to use the woocommerce_is_purchasable filter to set if a product can be purchased or not (which means, the add to cart may or may not show). Enjoy!
PHP Snippet: Deny Selling if a Product Has Sold More Than X Today
/**
* @snippet Limit Daily Sales For Product ID
* @how-to businessbloomer.com/woocommerce-customization
* @author Rodolfo Melogli, Business Bloomer
* @compatible WooCommerce 7
* @community https://businessbloomer.com/club/
*/
add_filter( 'woocommerce_is_purchasable', 'bbloomer_not_purchasable_after_daily_limit', 9999, 2 );
function bbloomer_not_purchasable_after_daily_limit( $is_purchasable, $product ) {
$limit_product_id = 12345; // SET YOUR PRODUCT ID HERE
if ( $product->get_id() !== $limit_product_id ) return $is_purchasable;
// GET TODAYS ORDERS AND LOOP
$all_orders = wc_get_orders(
array(
'limit' => -1,
'date_created' => date( 'Y-m-d' ),
'return' => 'ids',
)
);
$count = 0;
foreach ( $all_orders as $all_order ) {
$order = wc_get_order( $all_order );
$items = $order->get_items();
foreach ( $items as $item ) {
$product_id = $item->get_product_id();
if ( $product_id && $product_id == $limit_product_id ) {
$count = $count + absint( $item['qty'] );
}
}
}
// LIMIT 3 DAILY SALES
if ( $count >= 3 ) return false;
return $is_purchasable;
}
Hi. Fantastic work.
Is there a way to limit the stock based on a day selected from a callender field? So I only allow 3 to be sold on the date entered. This will allow future purchases to be limited.
Use case: Say I have a theater, and I only have 3 seats available. I would like to sell 3 tickets every day. So if all tickets are sold for today. I can try for a different date.
Hello Stefan, thanks so much for your comment! Yes, this is definitely possible, but I’m afraid it’s custom work. If you’d like to get a quote, feel free to contact me here. Thanks a lot for your understanding!
Can this be done 1 per customer id
Hi Jack, thanks so much for your comment! Yes, this is definitely possible, but I’m afraid it’s custom work. If you’d like to get a quote, feel free to contact me here. Thanks a lot for your understanding!
I cant seam to get this to work. Is there way to limit it per product tag instead of id?
Did you use the exact same code and test it with a Simple product? If not, give me more context please, because it works for me.
In regard to the other question, of course – anything is possible
Interesting snippet. Thank you very much
You’re welcome!