Create or Update thousands of woocommerce products via PHP

I have client with a cash register in the store. That register has an API from which I’m retrieving over 5000 products and syncing them with online store. I wrote plugin that triggers cron job every night, there is also manual triggering sync just in case of need. The issue is that sync lasts couple hours. Is there any way to make this faster? I’m using ec2 instance on AWS, PHP version is 7.2, WordPress and Plugins versions are always up to date.

Here is a peace of code where I’m creating or updating products:

public function parse_api_response($product) {
        //check if product is in DB
        $existingProduct = $this->checkIfProductExist($product);
        if ($existingProduct == null) {
            if (isset($product->StorageAmount) && $product->StorageAmount > 0) {
                $filter_res = array_values(array_filter($this->departments, function ($d) use ($product) {
                    return $d['department_id'] == $product->Department->Id;
                }));
                $cat = [];
                if (isset($filter_res[0]['categories'])) {
                    for ($i = 0; $i < count($filter_res[0]['categories']); $i++) {
                        $cat[$i] = $filter_res[0]['categories'][$i]['id'];
                    }
                }

                try {
                    $wcProduct = new WC_Product();
                    $wcProduct->set_name($product->Description);
                    $wcProduct->set_description($product->Description);
                    $wcProduct->set_short_description($product->Description);
                    $wcProduct->set_regular_price((string)$product->SellPrice);
                    $wcProduct->set_regular_price((string)$product->SellPrice);
                    $wcProduct->set_category_ids($cat);
                    $wcProduct->set_status("private");
                    $wcProduct->set_slug('pa_' . sanitize_title(strtolower($product->Description)));
                    $wcProduct->set_manage_stock(true);
                    $wcProduct->set_stock_quantity( $product->StorageAmount);
                    $product_id = $wcProduct->save();
                    update_post_meta($product_id, 'api_product_id', wc_clean($product->Id));
                    update_post_meta($product_id, 'item_number', wc_clean($product->ItemNumber));

                } catch (\Exception $e) {
                    echo $e->getMessage();
                }
            }
        } else {
            $wcProduct = new WC_Product($existingProduct);
            $wcProduct->set_manage_stock(true);
            $wcProduct->set_stock_quantity($product->StorageAmount);
            $wcProduct->set_regular_price((string)$product->SellPrice);
            try {
                $product_id = $wcProduct->save();
            } catch (\Exception $e) {
                echo $e->getMessage();
            }
        }
    }

0

Leave a Comment