$product->get_available_variations() reduces performance dramatically
-
Hi there,
In order to display an “Add to cart” button on the product preview showed in category archive page and in the product loops, I changed the file content-product.php in my child theme. I have a working solution BUT the performance is significantly affected. It adds ~15 sec. to the load time, depending on the number of products. Demo : vtest.naturalpes.ch/eshop
What I did is :
1) Get the type of product (simple or variable)
2) If variable, get the desired variation
3) Generate a button with a custom link that adds the variation to the cart
4) Log the time difference all along the code in order to measure performanceHere is the code snippet :
$t1 = round(microtime(true) * 1000); if ( $product->is_type( 'simple' ) ) { $add_to_cart_id = $product->get_id(); $add_to_cart_price = $product->get_price(); $add_to_cart_text = $add_to_cart_price . " " . get_woocommerce_currency_symbol(); $add_to_cart_text = $add_to_cart_price; $t2 = $t1-round(microtime(true) * 1000); } elseif ( $product->is_type( 'variable' ) ) { $variations = $product->get_available_variations(); $variation = $variations[0]; $t3 = $t1-round(microtime(true) * 1000); // Oils -> get higher price if(in_array(16, $productCatIds) OR in_array(39, $productCatIds) OR in_array(46, $productCatIds)){ $higher_price = 0; foreach ($variations as $var){ if ($var['display_price'] > $higher_price) { $variation = $var; $higher_price = $var['display_price']; } } $t4 = $t1-round(microtime(true) * 1000); } // Other categories -> get lower price else { $lower_price = 9999999; foreach ($variations as $var){ if ($var['display_price'] < $lower_price) { $variation = $var; $lower_price = $var['display_price']; } } $t5 = $t1-round(microtime(true) * 1000); } $add_to_cart_id = $variation['variation_id']; $add_to_cart_price = $variation['display_price']; $add_to_cart_text = reset($variation['attributes']) . " - " . $add_to_cart_price . " " . get_woocommerce_currency_symbol(); $add_to_cart_text = reset($variation['attributes']) . " - " . $add_to_cart_price; $t6 = $t1-round(microtime(true) * 1000); } ?>The logging demonstrates that $product->get_available_variations() takes a lot of time to run ($t3 = between 1000ms – 3000ms, for each product).
What is wrong in this code ? Is there an alternative to $product->get_available_variations() ?
Thanks in advance for your help.
Ruben
The page I need help with: [log in to see the link]
The topic ‘$product->get_available_variations() reduces performance dramatically’ is closed to new replies.