php - Wp-query output correct, but the loop shows one less item (only sometimes)

My site is making a strange bug, the code below works 99% of the times but every now and then it return only 2 items in

My site is making a strange bug, the code below works 99% of the times but every now and then it return only 2 items in the loop, even that the query results have more products

// get the cats this product is in
$terms = wp_get_post_terms($post->ID, 'product_cat');


$cats = array();
$total = array();
// if there is only one category jump out.
if (count($terms) == 1) {
    $cats = $terms[0]->term_id;    
}else{
    // remove anything that is a parent cat
    foreach ($terms as $k => $term) {
        if ($term->parent === 0) {
            unset($terms[$k]);
        } else {
            // build list of terms we do want (children)
            $cats[] = $term->term_id;
        }
    }
}
foreach ($terms as $k => $term) {
     $total[] = $term->count;
}
// wp_reset_postdata();


$related_products = new WP_Query(
    array(
        'posts_per_page' => 3
        'order' => 'DESC',
        'orderby' => 'rand',            
        'post_type' => 'product',
        'post__not_in' => $post->ID,
        'tax_query' => array(
            array(
                'taxonomy' => 'product_cat',
                'terms' => $cats,
            )
        ),
    ) 
);

I use this to check that the query results works fine every time, even when it only shows 2 results in the loop:

        echo "<pre>";
            var_dump($cats);
        echo "</pre>";

        echo 'Total products with these terms: '.array_sum($total);         

        echo "<pre>";
            $total = $related_products->post_count;
            echo 'Total in query: ';
            var_dump($total);

            // var_dump($related_products);             
        echo "</pre>";

you can check here under the Related Products section: /

It will mostly show fine, but sometimes if you refresh it will show only 2 products (like image attached)

Thanks a lot for any comments Santiago

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745451124a4628273.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信