Today, I came across a task of making a Magazine like homepage for a wordpress Template. The challenge is that there are multiple sections in the homepage that requires multiple loops – we’re talking about more than 5 loops. This is necessary because they are for different categories, different styling, and they are included in separate styles.
The problem is that sometimes posts/articles appear in one loop, because it satisfies the loop condition, and it also appears in another box. For example, one article will appear in the Featured box, because it is tagged as featured, and it will appear in 2 other boxes for categoris – TV, and Production.
Now the main task is to make the post only appear on one box.
There are plenty of discussions regarding this over the web. WordPress codex has an example. However it only shows two loops. The other solution is to use “$do_not_duplicate = $post->ID;“, i’m sure you have come across that. I am unsure if that can be used in more than 2 loops, but in my case i was not able to make it work.
What worked for me though is storing the post into an array. So each post that appears in the loop is added to an array, adding the data to the array as we go through the other loops. This means that we are sure that none of our posts are repeated.
Here’s an example of how to do it.
The first loop can start as any normal loop you want like, and add the $ids array.
$my_query = new WP_Query('tag=featured&posts_per_page=1');
$ids = array();
*This code display the latest post tagged “featured”.
For the next loops you need to just add an argument variable which is an array – $args_fp.
$args_fp = array( 'post__not_in' => $ids, 'category_name' => 'News', 'posts_per_page' => 4 ); $my_query = new WP_Query($args_fp); while ($my_query->have_posts()) : $my_query->the_post(); $ids[] = get_the_ID();
Notice the ‘ ‘post__not_in’ => $ids,‘ line? That tells your loop not to include posts that are already in $ids.
Then you will see ‘$ids[] = get_the_ID();‘ which basically stores the postIds that is called/statisfies your loop to include them in the array so they will be add to the ‘post__not_in’
As you build more loops, more ids will be stored in $ids.
I hope this helps

