【问题标题】:WP_Query with posts sorted by comments dateWP_Query,帖子按评论日期排序
【发布时间】:2022-02-03 20:11:51
【问题描述】:

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

【问题讨论】:

  • 欢迎来到 Stack Overflow!你已经尝试过什么?您自己的代码有没有遇到任何问题?
  • 我在wordpress codex中看到没有排序cmets日期参数,只有在发布日期之后。我试过类似的东西: $args = array( 'cat' => $category, $cmets = get_cmets( array( 'post_id' => $post->ID, 'status' => 'approve' ) ), 'orderby' => $cmets[0]->comment_date );不工作

标签: php sql wordpress


【解决方案1】:

这很有趣。可能有两种方法可以解决这个问题。 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 降序排序的帖子 喜欢:

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

希望对你有帮助:)

【讨论】:

  • 嗯.. 我想在类别页面上显示这个循环和帖子。抱歉,您的代码不起作用。如果我评论这一行:'meta_key' => '_recent_comment_date',循环显示帖子但顺序不正确
  • 好的。我只注意到在数据库中添加新评论时添加了 meta_key '_recent_comment_date'。我还需要将此添加到现有帖子中...
猜你喜欢
  • 2023-03-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-05
相关资源
最近更新 更多