widget loop: collect queried posts IDs in array to exclude these in main loop
-
I am currently building a magazine theme and need a little help handling multiple loops. I need to somehow collect the queried posts
post_ID
s in the widget code in order to exclude these posts from the main loop.So on the front page (= blog page) the theme displays the following:
- WIDGET 1: 3 featured posts (posts from category 123)
- WIDGET 2: the 5 latest posts from category XY
- WIDGET 2: the 5 latest posts from category ABC
- the main loop
Each post can have more than one category.
The main loop is supposed to exclude those posts that already have been queried by WIDGET 1 and WIDGET 2.So in the WP Codex there is a paragraph about how to do this with multiple loops. The solution looks like this:
For the custom loop
<?php $my_query = new WP_Query( 'category_name=featured&posts_per_page=2' ); while ( $my_query->have_posts() ) : $my_query->the_post(); $do_not_duplicate[] = $post->ID; ?>
For the main loop:
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); if ( in_array( $post->ID, $do_not_duplicate ) ) continue; ?>
**Idea**
As you can see, I use the same widget more than once. This makes me think I can’t just go and use$do_not_duplicate[] = $post->ID;
in my widget code because it’ll get overwritten, won’t it?How can I store the IDs of the posts that have already been queried by the widgets in a variable or an array to use them in my
index.php
file ?I’m glad if anyone could give his/her thoughts on this.
- The topic ‘widget loop: collect queried posts IDs in array to exclude these in main loop’ is closed to new replies.