Order posts by recent comments

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.