I’m wanting to order WordPress posts by the most recent comment. To the best of my knowledge this isn’t possible using the WP_Query object, and would require a custom $wpdb query, which I can easily write. However, I then don’t know how to setup the loop to run off this object.
Can anyone help?
Assign
to some variable $query. You can fiddle around with the 10 or the query itself. (I’m no SQL optimization ninja.) Then your code will look something like
This pattern is covered in more depth by the Codex.
I used a simpler, portion of a native WP in function. hope it helps and some one can continue to develop. Here is a simplified version that shows the title & excerpt of the post along with the comment content & author from the latest commented posts using get_comments.
OK guys,
A lot of great answers here, but obviously nobody’s taken the time to test them.
Hao Lian gets the credit for the first best original answer, but unfortunately his code doesn’t show posts without comments.
Captain Keytar is on the right track, but his code will display every single post and attachment as a separate result.
Here is a modified version of Captain Keytar but it limits the results to the type ‘post’.. that has been published (to avoid getting drafts!!)
This is an old question, but I had the same issue and found a much cleaner way to do this, so I’m posting it here in case it helps anyone.
If you use the posts_clauses filter you can then just modify the main query and still use The Loop and all the regular loop functions.
Note that I changed the sql slightly for my own purposes, but the general concept is the same.
As an addendum to Hao Lian’s answer, if you use the following query:
This mixes in posts that don’t have comments yet, and sorts them by post_date and max(comment_date).
Code suggested by Hao Lian works perfect except for the fact that we should add the following WHERE clause to avoid pulling POST with
comment_count = 0
, this situation is caused by spam comments.The WHERE clause to add is as follows:
Complete code after adding the where clause shoud look like following:
This can be done by combining WP_Comment_Query with WP_Query, like this:
I’m thinking that adding in the max function will screw up your results. MySQL isn’t going to pull the max from each one. It’s going to pull the max from the full set. This is the query that’ll get you your results:
After that, if you want to follow WP convention, use this, and then you can use the functions that most of your templates are using (based on the loop):
Get 3 newest comments for custom post type ‘question’ regardless of approvement:
Using Lucian’s BEAUTIFUL solution, I needed to alter/filter the existing WP_Query to sort posts by the latest comment. Here’s the code, tested & works perfectly: