Reputation: 239
In WooCommerce I basically need to set a stock quantity of 10 for 4 separate products so when someone purchases 1 of these products the overall stock level goes down to 9.
The stock quantity for these products has to be linked so when 1 is purchased the quantity for all of them goes down.
I can't simply set 1 product up as a 'variable product' to achive this as each product has to be a 'simple product'.
Does anyone know of a plugin or way of setting up WooCommerce to achieve this?
Upvotes: 0
Views: 846
Reputation: 253901
You could try this custom function that is using the woocommerce_thankyou
hook, to get first, the smallest stock value of the bought products in the customer order and then update all products with this stock value. This is untested, so you will have to give me some feed back on it.
Here is this code:
add_action( 'woocommerce_thankyou', 'updating_product_unified_stock', 10, 1 );
function unifying_product_stock($order_id){
$stock_updated = get_post_meta($order_id, 'stock_updated', true);
if(empty($stock_updated)):
// Inserting in the order meta data a custom field value to avoid repetition of this code,
// if the customer reload the "Order received" page…
update_post_meta($order_id, 'stock_updated', 'yes');
$products_stock_arr = array();
$products_ids = array();
// Getting the Order Object post data
$order = wc_get_order( $order_id );
foreach ( $order->get_items() as $item_id => $item ) {
$product_stock = get_post_meta($item_id, '_stock', true);
$products_stock_arr[] = $product_stock; // adding the product stock in the array
}
// Get the smallest stock value in the array of stock values
$new_stock_number = min($products_stock_arr);
// get all published simple products
$all_products = get_posts( array(
'post_type' => 'product',
'posts_per_page' => -1,
'post_status' => 'publish'
));
// Iterating through each published product
// UPDATING PRODUCTS WITH THE NEW STOCK VALUE:
foreach( $all_products as $product)
update_post_meta( $product_id, '_stock', $new_stock_number );
endif;
}
This code goes in function.php file of your active child theme (or theme) or also in any plugin php files.
Upvotes: 1