How to detect duplicate posts and remove them from loop?
Colormag Wordpress theme

How to detect duplicate posts and remove them from loop?

In Magazine WordPress theme, not showing duplicate post item is one of the most important feature. In your homepage, you might have several categories which may have been assigned to single post and you won’t want to show that post in every single category. Despite that every few, I mean really few themes were doing this. Ofcourse, it might be possible that I hadn’t looked into many themes into details but I couldn’t find.

Probably that’s why I assumed it would be nightmare. Especially when the posts are being fetched via widgets in the theme and that was the exact scenario in our ColorMag theme. We did talk about adding this feature but no one was willing to come forward and take this in hand. From the very begining of joining ThemeGrill, I was aware of ColorMag theme and it’s stats on downloads ( now active installs ). I always thought this feature must be added in ColorMag theme but I was too afraid even to try because I assumed it to be hard.

I had a not-so-clear concept of saving Post ID in array and checking everytime we run the query but I had no idea how that would work in widgets. Here, how I did it.

1. Defined a empty array in functions.php
2. Fetched that array in widget function of widget with global $arrayname
3. Now in WP_Query, checked if the post being displayed is alreay in array so that we can skip that specific post
4. If not skipped, add id of that post to array
5. Repeat Step 3 and 4 in other widgets

Since the array was declared in functions.php, it was available to any function using global keyword.

$donot_include = array();

global $donot_include;
if(in_array($post->ID , $donot_include)) continue;
$donot_include[] = $post->ID;

For every widgets.php, I repeated the above code and stopped duplicate posts from re-appearing.


Startups Enthusiast. Loves to code (PHP, JS). Occasional Blogger, wannabe Entrepreneur & Amateur Philosopher

Leave a Reply

Close Menu