Change stock_status upon order completion – WooCommerce
I am setting up a store which only ever has 1 of each item in stock.
I have the WooCommerce Manage Stock OFF, and only using the dropdown Stock Status to manage the ability for customers to buy or not buy.
After purchase I still want the product to be visible but unable for another person to buy it after it has been brought.
Question: How do I change the stock status of a product upon the successful purchase of a product?
Changing the stock status to ‘outofstock’
My Code so far:
add_action('woocommerce_payment_complete', 'wca_change_stock_status',10,3);
function wca_change_stock_status()
{
$out_of_stock_staus = 'outofstock';
global $product;
$product_id = $product->get_id();
// 1. Updating the stock quantity
update_post_meta($product_id, '_stock', 0);
// 2. Updating the stock quantity
update_post_meta($product_id, '_stock_status', wc_clean($out_of_stock_staus));
// 3. Updating post term relationship
wp_set_post_terms($product_id, 'outofstock', 'product_visibility', true);
// And finally (optionally if needed)
wc_delete_product_transients($product_id); // Clear/refresh the variation cache
}
EDIT:Below error was due to PayPal Sandbox not returning a completed order. Stock is now going down as expected.
Note, might be a seperate issue: I have tried stock level of 1. But after purchase the stock levels do not go down.
Leave an answer