Constructing the SQL query:
You can try the following:
/**
* Fetch comments' IDs for the most recently commented posts
* (only one comment per post)
*
* @param integer $count
* @return array
*/
function get_cids_wpse ( $count = 5 )
{
global $wpdb;
$sql = "SELECT MAX( comment_ID ) as cid
FROM {$wpdb->comments}
GROUP BY comment_post_ID
ORDER BY cid DESC
LIMIT 0, %d";
return $wpdb->get_cols( $wpdb->prepare( $sql, $count ) );
}
where I assume that the comments’ date have the same order as the IDs. If that’s not the case for your setup, then we need to adjust this further.
Usage examples:
If we need to get the last 5 comments per post, we can use:
$cids = get_cids_wpse( 5 );
$comments = array();
foreach( (array) $cids as $cid )
{
$comments[] = get_comment( $cid );
}
or this setup:
$args = array(
'include' => get_cids_wpse( 5 );,
'orderby' => '_include', //<-- custom parameter
);
$comments = get_comments( $args );
where we use this code snippet to order by the include values.
Notice: You could also expand this example further, with more comments db fields and then use the get_results()
method instead of get_col()
. Then you would only use a single db query to fetch all the comments data.