WooCommerce allows you to set your stock quantity for each and every product that you add. But what if you know that every item in your store will only be sold once? In that case, it’s worth it to save yourself the hassle of always needing to manually add the stock quantity, and set the deafult stock quantity to one.
At the same time, we can enable “Track stock quantity” by default and just to make sure, we’ll set enable “Limit purchases to 1 item per order” by default as well.
This is How You Do It
Using the Code Snippets plugin, add this code:
add_action('save_post_product', 'auto_set_stock_and_limit_purchase_to_one', 20, 3);
function auto_set_stock_and_limit_purchase_to_one($post_ID, $post, $update) {
if ($update) return;
$product = wc_get_product($post_ID);
if ($product && $product->get_type() === 'simple') {
$product->set_manage_stock(true); // Enable "Track stock"
$product->set_stock_quantity(1); // Set stock quantity
$product->set_stock_status('instock'); // Set stock status to "In stock"
$product->set_sold_individually(true); // Limit to 1 per order
$product->save();
}
}
In Short
Your WooCommerce shop is now updated to do the following:
- Tracks stock.
- Sets stock quantity to 1 by default.
- Marks it as in stock.
- Prevents user from buying 2 copies of the same item.
Mari's Note
♥ I hope my post was useful to you! If this post helped you in any way, please consider supporting me by making a small donation via my Ko-Fi page!