Slow Query with more 100 products

I’v created function to get all products of a category, and remove product with same meta_value (CIP). All works fine, but if category have more than 100 products my query is very very slow… for 2300 products times to view result are 35″ or more…

What is wrong ?

function get_all_product_in_selected_category($atts){
// Get the category
$catsearched = $atts[‘category_id’];

// Get all product of categoryselected
$product_args = array(
‘post_type’ => ‘product’,
‘post_status’ => ‘publish’,
‘posts_per_page’ => -1,
‘fields’ => ‘ids’, // Only return product IDs
‘tax_query’ => array(
array(
‘taxonomy’ => ‘product_cat’,
‘field’ => ‘id’,
‘terms’ => $catsearched,
‘operator’ => ‘IN’,
))
);

$products = get_posts($product_args);

if(count($products) > 0)
{
// Search CIP by product ID on category
foreach ( $products as $id )
{
$cip = $product_obj[‘product_cip’]=get_post_meta($id,’product_cip’);
//echo ‘Cip = ‘.$cip[0].’, ‘;
$arrayCip[] = $cip[0];
}
//echo ‘<b>TotalNumberOfCIP = ‘.count($arrayCip).'</b>’;

// Remove same cip from category
$result = array_unique($arrayCip);

//print_r($result);
//echo ‘<b>TotalNumberOfUniqueCIP = ‘.count($result).'</b>’;

// Get productID by CIP
foreach ($result as $v)
{
$product = array
(
‘post_type’ => ‘product’,
‘posts_per_page’=> -1,
‘meta_query’ => array
(
array(
‘key’ => ‘product_cip’,
‘value’ => $v,
‘compare’=> ‘=’
)
),
‘fields’ => ‘ids’
);
$product_post = get_posts($product);
//echo ‘Uniques CIP = ‘.$product_post[0].’, ‘;

$a[] = $product_post[0];
//echo count($product_post);
}

// If products exist, show products
if(count($a) > 0)
{
$product = array
(
‘post_type’ => ‘product’,
‘posts_per_page’=> -1,
‘meta_key’ => ‘product_cip’,
‘post__in’ => $a
);

$allproduct = get_posts($product);
foreach($allproduct as $allp) {
$arrayall[] = $allp->ID;
}

$result = implode(“,”, $arrayall);

return $result;
}
else
{
return 0;
}
}

}

Thanks,

Read more here:: Slow Query with more 100 products

Leave a Reply

Your email address will not be published. Required fields are marked *