I need to have some of my product variations to use the same stock and so i created this function.
Updating the stock works fine but i still have one problem.
This is my product structure :
Product A–> variation 1, variation 2 = group1 ; variation 3, variation 4 = group2 … (same SKU)
Product B–> variation 1, variation 2 = group1 ; variation 3, variation 4 = group2 … (same SKU)
Product C–> variation 1, variation 2 = group1 ; variation 3, variation 4 = group2 … (same SKU)
I suppose it’s not the best way to do it but I already have 50 products and as many variations like this, so I would like not to redo everything from scratch.
That’s why i need to add a SKU check in order to only update products/variations that have the same SKU.
add_action( 'woocommerce_order_status_processing', 'rudr_update_shared_stock' );
function rudr_update_shared_stock( $order_id ) {
$order = wc_get_order( $order_id );
$items = $order->get_items();
foreach ( $items as $item ) {
$product = $item->get_product();
$product_id = $product->get_id();
$group = get_post_meta( $product_id, 'custom_field', true );
if ( ! empty( $group ) ) {
$args = array(
'post_type' => 'product_variation',
'post_status' => 'publish',
'meta_query' => array(
array(
'key' => 'custom_field',
'value' => $group,
'compare' => '=',
)
)
);
$products = new WP_Query( $args );
if ( $products->have_posts() ) {
$lowest_stock = PHP_INT_MAX;
$ordered_product_stock = $product->get_stock_quantity();
while ( $products->have_posts() ) {
$products->the_post();
$product_id = get_the_ID();
$product = wc_get_product( $product_id );
$current_stock = $product->get_stock_quantity();
if ( $current_stock < $lowest_stock ) {
$lowest_stock = $current_stock;
}
}
wp_reset_postdata();
$args = array(
'post_type' => 'product_variation',
'post_status' => 'publish',
'meta_query' => array(
array(
'key' => 'custom_field',
'value' => $group,
'compare' => '=',
),
array(
'key' => '_stock',
'value' => $lowest_stock,
'compare' => '>',
)
)
);
$products = new WP_Query( $args );
if ( $products->have_posts() ) {
$total_quantity = $item->get_quantity();
while ( $products->have_posts() ) {
$products->the_post();
$product_id = get_the_ID();
$product = wc_get_product( $product_id );
$current_stock = $product->get_stock_quantity();
$new_stock = $current_stock - $total_quantity;
if ( $product_id == $item->get_variation_id() ) {
$new_stock = $ordered_product_stock - $total_quantity;
} elseif ( $new_stock < 0 ) {
$new_stock = 0;
}
$product->set_stock_quantity( $new_stock );
$product->save();
}
wp_reset_postdata();
}
}
}
}
}