0

I have stock items with variations all of which have stock management; The problem is when I do sell a stock variation item the parent item stock count does not reduce !

Example:- I have a parent code which is a T-SHIRT and 3 variations S/M/L these variations have a combined stock value of 30 (10 each size) then I want my parent code to also show a stock value of 30; currently when i sell a stock variation item it only reduces the stock for that item and not the Parent item(sku).

Is there a plugin or code which will allow me to do this ?

jww
  • 97,681
  • 90
  • 411
  • 885
BASit Bulbulia
  • 229
  • 3
  • 16
  • https://wordpress.org/support/topic/woocommerce-count-the-number-of-products-not-only-within-the-category/ – NickSlash Jul 28 '19 at 09:54
  • Nick, The page you directed me refers to a "default WooCommecrce Product Category widget" I just can't seem to find this widget any help will be much appreciated. – BASit Bulbulia Jul 28 '19 at 11:04

1 Answers1

1

I tested the code and it worked, but please make some more tests before make it live. Code goes to functions.php of your theme or child theme.

add_action( 'woocommerce_reduce_order_stock', 'lets_reduce_parent' );

function lets_reduce_parent( $order_id ) {
  $order = wc_get_order( $order_id );
  foreach( $order->get_items() as $item_id => $item ){
      $parent_id = $item->get_product_id();
      $child_id = $item->get_variation_id();
      $quantity = $item->get_quantity();

      if($child_id == 0) return;
      else
      {
          $parent_product = wc_get_product( $parent_id );
          $stock = $parent_product->get_stock_quantity();
          $new_stock = $stock - $quantity;
          wc_update_product_stock( $parent_product, $quantity, 'decrease' );
          $order->add_order_note( "Parent Product ID: $parent_id - Stock Reduced: $stock -> $new_stock");
      }
  }
}

Ref-1: Woocommerce custom stock update after successful order

Ref-2: Get Order items and WC_Order_Item_Product in WooCommerce 3

I hope this will help. Please inform me if you have any problems. Have a good day.

MrEbabi
  • 740
  • 5
  • 16