'WP_Query with posts sorted by comments date

Same as title: I need make Wordpress loop that will display posts sorted by comments date. Like on forum, first is post with the latest comment.



Solution 1:[1]

It is interesting. There might be two approached which can resolve this. 1 -

$args = array(
    'status' => 'approve',
    'order' => 'DESC'
);

$comments = get_comments( $args );
$ids = array();

foreach ( $comments as $comment ) {

     $post = get_post( $comment->comment_post_ID );

     if(!in_array($post->ID, $ids):
        $ids[] = $post->ID;
        echo $post->title;
     endif;

}

2 - Add a action to add a meta to the post for the recent comment date.

add_action('comment_unapproved_to_approved', 'wpc_2511_comment_approved');
function wpc_2511_comment_approved($comment) {
    $comment_post_ID = $comment->comment_post_ID;
    $date = $comment->comment_date;
    update_post_meta( $comment_post_ID, '_recent_comment_date', $date );

}

Then write the query string to get the posts sorted by meta_key & meta_value Descending Like:

$args = array(
  'post_status'       => 'publish',
  'post_type'         => 'post'
  'meta_key'          => '_recent_comment_date',
  'orderby'           => 'meta_value_num',
  'order'             => 'DESC'
);

Hope this will help you :)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Malaya Sahu