WordPress: Recent Comments by Category

Yet another WordPress code snippet ;) I’ve got two major categories in my upcoming project – Blogs and Arts. In the archive, somewhere in the sidebar, I’d like to output the recent comments only from the chosen category, excluding the ones that are from the other category. The most difficult part here is to figure out proportions, because running this hack recursively may eat up all your memory. For instance you have two categories and you’d like to output 10 comments for each. The posts in the first category get commented twice as often as the posts in the second category, so the proportions here would be approximately 2:1, but it also depends on how often “the switch” is.

For instance, taking 20 comments in a stream (one after the other, ordered by publish date), imagine the first 10 are from the first category and the last 10 are from the second. You’d have to query at least 20 comments to retrieve the needed amount. Here’s another example – take 90 comments in a stream, 60 are from the first, 30 are from the second. You need 10 comments for each, your ratio is 2:1 but you need to cycle at least 70 comments to make sure you display 10 from the second category. I know this is insane, but you’ll get my point when you’ll lack a few comments in your sidebar, especially if the widget is titled “10 recent comments” ;)

Here’s the code:

<?php
$show_comments = 10;
$i = 0;
$comments = get_comments("number=50&status=approve");
foreach ($comments as $comment)
{
    $comm_post_id = $comment->comment_post_ID;
    if (!in_category("blogs", $comm_post_id))
        continue;
    $i++;

    // Output the comment, author and whatever you need
    // I'll just output the comment excerpt to keep my code simple
    ?><li><?php comment_excerpt(); ?></li><?php

    if ($i >= $real_comments) break;
}
?>

So 50 is the number that you need to figure out. Don’t take too much if you don’t need to, otherwise you’ll just be getting too much rows from your database that you’ll never use and slow down your application. Run a few tests, use a logger for debugging and make sure you’re caching the results.