在WordPress中按最后评论日期排序帖子


Order posts by last comment date in WordPress

我使用get_comments()get_post()的组合来显示按评论日期排序的帖子列表。

裁判:

http://codex.wordpress.org/Function_Reference/get_commentshttps://codex.wordpress.org/Function_Reference/get_post

我的代码:

$args = array(
    'status' => 'approve',
    'order' => 'DESC'
);
$comments = get_comments( $args );
foreach ( $comments as $comment ) {
     $post = get_post( $comment->comment_post_ID );
     echo $post->post_title;
}

这种方法的问题是,如果一个帖子有多个评论,那么帖子列表将包含重复的帖子标题。

如何删除重复项?

更新:这种最初的方法做了很多不必要的跑腿工作。例如,在有很多帖子和评论的网站上,查询将拉回很多不必要的评论。

更新问题:如何按评论日期排序帖子列表?

这是一个有趣的方法…但是,我想你可以用post ID填充一个数组,然后稍后再检查它们。

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