Here are the codes that I use to avoid displaying duplicate posts when I use multiple loops to pull in the most recent posts from different categories on a WordPress page.
Here is the code that I use to display the most recent posts from specific categories on a WordPress page:
<h3>Latest posts</h3><br/>
<?php
//for categories 1,5,3, show 1 post
$cat_args=array(
'include' => '1,5,3',
'orderby' => 'name',
'order' => 'ASC'
);
$categories=get_categories($cat_args);
foreach($categories as $category) {
$args=array(
'showposts' =>3,
'category__in' => array($category->term_id),
'caller_get_posts'=>1
);
$posts=get_posts($args);
if ($posts) {
echo '<p><h4>Latest <a href="' . get_category_link( $category->term_id ) . '" title="' . sprintf( __( "View all posts in %s" ), $category->name ) . '" ' . '>' . $category->name.' Posts</a>: </h4></p> ';
foreach($posts as $post) {
setup_postdata($post); ?>
<p style="margin-left:20px;">
<a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></p>
<?php
} // foreach($posts
} // if ($posts
} // foreach($categories
?>
And here is the same code with the lines added (highlighted in red) that will prevent your WordPress loops from displaying duplicate posts:
<h3>Latest posts</h3><br/> <?php //for categories 1,5,3, show 1 post $cat_args=array( 'include' => '1,5,3', 'orderby' => 'name', 'order' => 'ASC' ); $do_not_duplicate = array(); $categories=get_categories($cat_args); foreach($categories as $category) { $args=array( 'showposts' =>3, 'post__not_in' => $do_not_duplicate, 'category__in' => array($category->term_id), 'caller_get_posts'=>1 ); $posts=get_posts($args); if ($posts) { echo '<p><h4>Latest <a href="' . get_category_link( $category->term_id ) . '" title="' . sprintf( __( "View all posts in %s" ), $category->name ) . '" ' . '>' . $category->name.' Posts</a>: </h4></p> '; foreach($posts as $post) { setup_postdata($post); $do_not_duplicate[] = $post->ID; ?> <p style="margin-left:20px;"> <a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></p> <?php } // foreach($posts } // if ($posts } // foreach($categories ?>
As always, just let me know if you run into any issues or have any questions.
