WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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

share|improve this question

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() ) {

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.

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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