Using query_posts, how can I order the list of posts so the ones with the most recent comments are at the top?

I'm looking for something similar to how Questions here on SE are ordered when you sort by "Active."

1 Answer 1


I wouldn't use query_posts(). That particular function is meant for making changes to a specific query ... and it's limited enough that you can't get the kind of custom functionality you need out of it.

Rather, I'd use a custom query. What you'll want to do is query approved comments sorted by their post/approval date and join that with the posts in your database. If a post doesn't have any comments, it would automatically be filtered out based on this criteria.

A very simple pseudo-code example:

$qstr = 'SELECT * FROM wp_posts ON (wp_posts.post_id = wp_commnets.comment_post_id) WHERE wp_comments.comment_approved='approved' ORDER BY wp_comments.comment_date';
$my_query = new WP_Query($qstr);

while($my_query->have_posts() ...

Basically, you're selecting posts based on specific criteria related to data in the comments table. Using a direct query requires a certain depth of knowledge regarding SQL statements and the WP database structure, though ... so it's not usually my first recommendation, but should work in your case.

Just remember that the code above is pseudo-code ... meaning I made it up off the top of my head, it might not work, and you should only use it as a conceptual example.

For reference:

  • Your code has some syntax errors :-) Jul 15, 2014 at 8:03
  • Pseudo-code. Note I mentioned that both before and after the code snippet.
    – EAMann
    Aug 23, 2014 at 2:01

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.