Exclude posts from first loop in second loop
-
Hi,
I’ve created a related posts function for the end of my single.php that has 2 loops. The first loop displays related posts by tag and then if there’s not enough of those then the second loop kicks in and displays some recent posts from the same category.
The idea is that i always want to show 4 related posts but i haven’t always got enough related by tag so when that happens i display a few from the same category to pad it out.
Both loops exclude the current post id, however, the problem i have is that it is possible for a post to be returned in the first tag loop and the second by-category loop, so i end up with 2 of the same in the related posts
What I want to do is exclude any posts returned in the first by-tag loop from the second by-category loop.
I’ve been trying to implement something this solution but not much luck
https://stackoverflow.com/questions/12539952/two-loops-exclude-post-from-first-loop-in-second-loop
Here’s my code:
<?php $orig_post = $post; global $post; $tags = wp_get_post_tags($post->ID); $max_articles = 4; // How many articles to display $cnt = 0; if ($tags) { $tag_ids = array(); foreach($tags as $individual_tag) $tag_ids[] = $individual_tag->term_id; $args=array( 'tag__in' => $tag_ids, 'post__not_in' => array($post->ID), 'posts_per_page'=> $max_articles, // Number of related posts to display. 'caller_get_posts'=>1 , 'tag__not_in' => array('480'), 'orderby' => 'date', 'order' => 'DESC' ); $my_query = new wp_query( $args ); $exclude_featured = array(); while( $my_query->have_posts() ) { $my_query->the_post(); $cnt++; $exclude_featured = $post->ID; ?> <?php the_title(); ?> <? } } $post = $orig_post; if ($cnt < $max_articles) { $args=array( 'category_name' => $category[0]->cat_name, 'post__not_in' => array($post->ID), 'caller_get_posts'=>1 ); $blah=array( 'post__not_in' => array($exclude_featured) ); $mergeblah = array_merge( $args, $blah ); $relQuery = new WP_query( $mergeblah ); if($relQuery->have_posts()) : while($relQuery->have_posts()) : $relQuery->the_post(); $cnt++; if ($cnt > $max_articles) break; ?> <?php the_title(); ?> <?php endwhile; else : //do nothing endif; } wp_reset_postdata(); ?>
Any pointers much appreciated.
Thanks,
Kes
- The topic ‘Exclude posts from first loop in second loop’ is closed to new replies.