0

Lets say I have 5 posts where most recent comments placed. How can I get one comment per each of these posts? I want to use get_comments(). Is it possible?

Post1: Comment 1
       Comment 6
Post2: Comment 2
Post3: Comment 5
       Comment 7
Post4: Comment 3
       Comment 4
Post5: Comment 8

The result should look like this:

Comment8
Comment7
Comment6
Comment4
Comment2
  • So 5 calls to get_comments followed by some logic to merge them all together. Can I ask why you're trying to do this? – Tom J Nowell Nov 14 '14 at 12:51
  • @TomJNowell Because I want to show 5 last commented posts with one last comment rather than 5 comments from one post. I think it would be more informative for my users – Epsiloncool Nov 14 '14 at 12:53
  • @PieterGoosen Please could you send an example of parameters? – Epsiloncool Nov 14 '14 at 12:53
  • @TomJNowell The question is: which logic I have to use? – Epsiloncool Nov 14 '14 at 12:54
  • 1
    The logic needed is just basic pure PHP array skills, every time you grab a comment you put it in an array. At the end you display the things in the array – Tom J Nowell Nov 14 '14 at 13:04
1

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.

  • Thanks, it works as expected. Could I use array of IDs to get all comments in one get_comments() call instead of cycling over them? – Epsiloncool Nov 14 '14 at 14:45
  • ok great, I updated the answer. – birgire Nov 14 '14 at 14:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.