I’m trying to create a function that shows the 10 most recently active WordPress posts based on comment activity. But I’m running into an issue with duplicates in the results. Here’s what I’ve got so far:
function get_recent_active_posts() {
global $db, $post_comments;
$limit = 10;
if (!$post_comments = cache_fetch('active_posts', 'recent')) {
$post_comments = $db->query("
SELECT comment_time, commenter, commenter_website, comment_id, post_id, comment_text
FROM comments_table
WHERE is_approved = 1
ORDER BY comment_time DESC
LIMIT $limit
");
cache_store('active_posts', $post_comments, 'recent');
}
}
Is there a way to modify this MySQL query or use a different approach to filter out the duplicate posts? I’ve heard about DISTINCT and GROUP BY but I’m not sure how to apply them here. Any suggestions would be really helpful!
Based on my own experience, using GROUP BY to keep only the latest comment per post really cleared up the duplicate issues. I tweaked the query so it first selects the most recent comment time for each unique post and then joins that result back to the main comments table. This lets you get all the detailed comment data for just that comment, avoiding the duplicate post problem. Adjusting the query like this should fit well into your current setup on WordPress.
I’ve encountered this issue before, and here’s what worked for me. Instead of querying the comments table directly, consider using WordPress’s built-in functions. The WP_Query class with ‘orderby’ => ‘comment_date’ can handle this elegantly. Here’s a snippet:
This approach leverages WordPress’s core functionality, avoiding direct database queries and potential caching issues. It automatically handles duplicates and gives you the most recently active posts based on comments. Plus, it’s more maintainable in the long run.
hey, have you tried using DISTINCT in your query? it might help. something like:
SELECT DISTINCT post_id, comment_time, commenter, commenter_website, comment_id, comment_text
FROM comments_table
WHERE is_approved = 1
ORDER BY comment_time DESC
LIMIT $limit
this should grab unique posts based on the latest comment. hope it helps!