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 wordpress.org 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.
One day, I came across this quote somewhere on internet,
"Everyday do something that scares you". I don’t know how true were those words but again I thought maybe I should give it a try. That’s different part of story here. I mostly write about such things here -> Life.
So, today I thought of giving this a try and I was amazed by how easy it was than I supposed it to be. I did had to 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();
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.