Example #1
0
 /**
  * Change the product stock in the given order item.
  *
  * @param array  $item   the order data
  * @param string $action STOCK_REDUCE_ACTION | STOCK_INCREASE_ACTION
  */
 protected function change(array $item, $action = self::STOCK_REDUCE_ACTION)
 {
     $productID = $item['product_id'];
     $productObject = wc_get_product($productID);
     $productLang = pll_get_post_language($productID);
     $variationID = $item['variation_id'];
     /* Handle Products */
     if ($productObject && $productLang) {
         /* Get the translations IDS */
         $translations = Utilities::getProductTranslationsArrayByObject($productObject);
         /* Remove the current product from translation array */
         unset($translations[$productLang]);
         $isManageStock = $productObject->managing_stock();
         $isVariation = $variationID && $variationID > 0;
         $method = $action === self::STOCK_REDUCE_ACTION ? 'reduce_stock' : 'increase_stock';
         $change = $action === self::STOCK_REDUCE_ACTION ? $item['qty'] : $item['change'];
         /* Sync stock for all translation */
         foreach ($translations as $ID) {
             /* Only if product is managing stock */
             if ($isManageStock) {
                 if ($translation = wc_get_product($ID)) {
                     $translation->{$method}($change);
                 }
             }
             $general = Settings::getOption('general', MetasList::getID(), array('total_sales'));
             if (in_array('total_sales', $general)) {
                 update_post_meta($ID, 'total_sales', get_post_meta($productID, 'total_sales', true));
             }
         }
         /* Handle variation */
         if ($isVariation) {
             $posts = Variation::getRelatedVariation($variationID);
             foreach ($posts as $post) {
                 if ($post->ID == $variationID) {
                     continue;
                 }
                 $variation = wc_get_product($post);
                 if ($variation && $variation->managing_stock()) {
                     $variation->{$method}($change);
                 }
             }
         }
     }
 }