0

Guys I'm dying to find an answer to this problem, I need the wp query to order by recent comments so I can output posts that have recently been commented on (I'm trying to get something like a Recent activity/What's new? thingy as in vBulletin forums). I already searched the whole internet and found a few solutions, but NONE of them actually work.. :-S

1 Answer 1

3

You can use the following code, which first gets the most recent comments, then using the post_ids associated with those comments, queries the database for those posts:

// Get the 5 most recent comments
$recent_comments = get_comments( array(
    'orderby' => 'comment_date',
    'number' => 5
) );

// If there are any posts with comments
if ( count( $recent_comments ) > 0 ) {

    // Get the post ID associated with each comment
    $post_ids = array();
    foreach ( $recent_comments as $comment )
        $post_ids[] = $comment->comment_post_ID;

    // Query for the posts with the IDs collected
    $posts_with_recent_comments = new WP_Query( array(
        'post__in' => array_unique( $post_ids )
    ) );

    // Get your loop on
    if ( $posts_with_recent_comments->have_posts() ) {
        while ( $posts_with_recent_comments->have_posts() ) {
            $posts_with_recent_comments->the_post();
        }
    }
}

One issue to be aware of is that you will not always get 5 posts with this code. The get_comments function as shown above will return the 5 most recent comments on the site. In the event that 3 of these comments are on the same post, you actually will only have 3 unique post IDs that you are sending to the query for the posts. This code shows you the general way of getting the job done and you'll have to spend some time working around the issue I raised.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.