Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialJake Bolton
1,956 PointsMy Wordpress category page is repeating posts of specific categories, is there a way to stop this?
I hope one of you fine people can help. I'm trying to create a category page with a list of clickable categories. I've set this up, but the page is displaying posts, with more that one category, multiple times.
I only want each post to display once.
I know this is to do with the query I'm using but just need to right syntax.
Hope you can help.
Thanks, Jake
2 Answers
Joel Bardsley
31,249 PointsHi Jake,
You could create an empty array before starting the loop, then as the loop runs it inserts each post ID into the array. This way you have something to check against on each iteration of the loop.
<?php
// Query has already been set up
if ( have_posts() ) {
// Create an empty array to store the post IDs in.
$post_ids = array();
while ( have_posts() ) {
// Store the current post ID in a variable
$current_post_id = get_the_ID();
// Check if the current post ID has already been added to the new array
if (in_array($current_post_id, $post_ids)) {
continue; // It's already been added, let's skip to the next iteration of the while loop.
}
// It hasn't already been added, let's display it.
the_post();
// Now that it's been displayed, let's add the id to the array so it doesn't get displayed again:
$post_ids[] = $current_post_id;
}
}
?>
Went a bit over the top with the comments, but hopefully the idea is clear enough and it comes in useful for your current project.
If you're struggling to understand anything I've written above, or get stuck trying to apply it to your existing code, let me know.
Jake Bolton
1,956 PointsHi Joel,
Thanks so much for responding. In the end I simply removed the custom query.
I used the standard loop and before I just included: // get all the categories from the database $cats = get_categories(); I've also applied this to archive.php
Makes me realise how smart Wordpress is, it does most of the work as long as you name your template correctly. Thanks again.