WordPress – Don’t display posts which were already displayed in another loop

I hace 2 sections on my site: first is for popular posts (based on views) and the second section is for the recent posts.
If the post is already in the popular posts section, I don’t want it to be displayed in the “Recent posts” section. Below is my code. In the first loop I’ve created an array to store all post ID’s which are in that section. In the second loop I check if the id is in that array (may be not the best solution).
For some reason it only works with the first duplicate, even though $cont becomes true required amount of times(I checked with echo). So what gives?

 <?php
    $popularpost = new WP_Query( array( 'posts_per_page' => 4, 'meta_key' => 'wpb_post_views_count', 'orderby' => 'meta_value_num', 'order' => 'DESC'  ) );
    $counter=0;
    $post_ids = array();
    while ( $popularpost->have_posts() ) : $popularpost->the_post(); 
        $postID = get_the_ID();
        $post_ids[$counter] = $postID;
     ?>
    <a href="<?php the_permalink(); ?>" class="" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a>

    <?php $counter++; ?>
    <?php   endwhile; ?>

    <?php $myquery = new WP_Query('posts_per_page=6');
    while ( $myquery->have_posts() ) : $myquery->the_post(); ?>
    <?php $post_id = get_the_ID(); ?>
    <?php $post_ids_length = count($post_ids); ?>
    <?php for ($i=0; $i < $post_ids_length; $i++) {
            if ($post_id == $post_ids[$i]) {
                $cont = "true";
            } else {
                $cont = "false";
            }
    } ?>
    <?php if ($cont == "true") {
        continue;
    } ?>

    <a href="<?php the_permalink(); ?>" class=""><?php the_title(); ?></a>
    <?php endwhile; ?>

Read more here: WordPress – Don’t display posts which were already displayed in another loop

Leave a Reply

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