Huge php memory usage while updating woocommerce products

238 Views Asked by At

I have written a small php script to programmatically update woocommerce products from an erp. Each update needs to update ~1000 products and in the end i have around 1gb of ram usage in the php process.

the $all_products variable is an object which comes from a soap request through the erps web services.


foreach ($all_products as $i => $product) {
    //print_r(round(memory_get_usage()/1024) .'K<br/>');


        $totalcounter++;
        $product_id = wc_get_product_id_by_sku( $product->ItemCode );
        //print_r('After get id by sku'.round(memory_get_usage()/1024) .'K<br/>');
        if ($product_id != '0') {
            
            $update_product = newUpdateProduct($product,$product_id);
            unset($update_product);
            unset($product_id);
            unset($product);
            print_r('after update'.round(memory_get_usage()/1024) .'K<br/>');
            $successcounter++;
            echo $successcounter.' Επιτυχής εγγραφή: '. $product->ItemCode;
wp_cache_flush();
}

i use the following function in order to update the products:

    function newUpdateProduct($options,$product_id) {
        $original_product_id = apply_filters( 'wpml_object_id', $product_id, 'product', FALSE, 'el' );
        $translated_product_id = apply_filters( 'wpml_object_id', $product_id, 'product', FALSE, 'en' );
        $price = round($options->ItemRetail,4);
    
        $working_product = wc_get_product ($original_product_id );
        $working_product->set_name($options->ItemDescr);
        $working_product->set_weight($options->ItemWeight);
        $working_product->set_price($price);
        $working_product->set_regular_price($price);
        $working_product->set_description($options->ItemNotes);
        $working_product->set_short_description($options->ItemDescr2);
        $working_product->update_meta_data('wholesale_price',$options->ItemWholesale);
    
        $working_product->save();
        
        if ($translated_product_id) {   
            $working_product = wc_get_product ($translated_product_id );
            $working_product->set_weight($options->ItemWeight);
            $working_product->set_price($price);
            $working_product->set_regular_price($price);
            $working_product->update_meta_data('wholesale_price',$options->ItemWholesale);
            
            $working_product->save();
            
        }
        unset($price);
        unset($working_product);
        unset($original_product_id);
        unset($translated_product_id);
        return 'ok';
    }

After $all_products is returned, the php process has usage of 140mb and it's increasing around 600-700kb after each product update. As you can see i use unset for each declared variable. I'm also flushing WP cache through wp_cache_flush() before the end of the loop.

What am i missing here?

0

There are 0 best solutions below