Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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."

share|improve this question
add comment

1 Answer

up vote 1 down vote accepted

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:

share|improve this answer
add comment

Your Answer

 
discard

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.