Reputation: 23
We run a self-storage system with WooCommerce and we use WooCommerce Subscriptions plugin. Our storage units is a unique product with a Variable Subscription. Each variation has a different billing period (1 month, 3 months, 6 months and 12 months). I need the whole parent product, or at least all variations, to be out of stock if one variation is out of stock.
I didn't find any related setting and I didn't find how to make that possible yet.
Any help is appreciated.
Upvotes: 0
Views: 1603
Reputation: 253901
The following will make all variations out of stock (for specific variable product(s)), when one variation is out of stock (also works with WooCommerce subscriptions):
add_filter('woocommerce_available_variation', 'set_all_variations_out_of_stock', 10, 3 );
function set_all_variations_out_of_stock( $data, $product, $variation ) {
// Set the Id(s) of the related variable product(s) below in the array
if( in_array( $product->get_id(), array(738) ) ){
$out_of_stock = false; // initializing
// Loop through children variations of the parent variable product
foreach( $product->get_visible_children() as $_variation_id ) {
if( $_variation_id != $data['variation_id'] ) {
$_variation = wc_get_product($_variation_id);
if( ! $_variation->is_in_stock() ) {
$out_of_stock = true; // Flag as out of stock
break;
}
}
}
if ( $out_of_stock ) {
$data['availability_html'] = '<p class="stock out-of-stock">'. __('Out of stock', 'woocommerce') .'</p>';
$data['is_in_stock'] = false;
}
}
return $data;
}
Code goes in function.php file of your active child theme (active theme). Tested and works.
Important note:
Stock can be managed on the parent variable product.
- Enable stock management on the variable product (on Inventory tab) and set the stock there.
- Disable stock management on each variation for this variable product.
You are done. The stock management is now handled on the variable product.
Upvotes: 2