WP_Query,帖子按评论日期排序

时间:2019-03-19 12:59:35

标签: php sql wordpress

与标题相同:我需要使Wordpress循环显示按评论日期排序的帖子。 像在论坛上一样,首先是发表最新评论。

1 个答案:

答案 0 :(得分:0)

这很有趣。可能有两种方法可以解决此问题。 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_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 );

}

然后编写查询字符串以获取按meta_key和meta_value Descending排序的帖子 喜欢:

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

希望这会对您有所帮助:)