WordPress评论排序:能否按用户角色分组展示评论?
当然可以实现!要按用户角色分组展示WordPress评论(先显示订阅者评论,再显示非注册用户评论),有两种实用方案,根据你的需求选就行:
方法一:全局修改评论查询(全站生效)
如果你希望所有页面的评论区都自动按这个规则排序,可以通过pre_get_comments钩子修改默认的评论查询逻辑。把下面的代码添加到你的主题(或子主题)的functions.php文件里:
add_action('pre_get_comments', 'sort_comments_by_subscriber_first'); function sort_comments_by_subscriber_first($query) { // 只修改前台的主评论查询,不影响后台操作 if (!is_admin() && $query->is_main_query()) { // 1. 获取所有订阅者用户的ID $subscriber_ids = get_users(array( 'role' => 'subscriber', 'fields' => 'ID' )); // 2. 获取订阅者发表的所有评论ID $subscriber_comment_ids = get_comments(array( 'user_id' => $subscriber_ids, 'fields' => 'ids' )); // 3. 获取非注册用户(访客)的所有评论ID $guest_comment_ids = get_comments(array( 'user_id' => 0, 'fields' => 'ids' )); // 4. 合并评论ID数组:订阅者评论在前,访客评论在后 $sorted_comment_ids = array_merge($subscriber_comment_ids, $guest_comment_ids); // 5. 让查询只包含这些ID,并按我们合并的顺序输出 $query->set('comment__in', $sorted_comment_ids); $query->set('orderby', 'comment__in'); } }
这段代码的逻辑很清晰:先筛选出订阅者的评论,再筛选访客评论,合并后强制查询按这个顺序输出,自动实现分组展示。
方法二:模板内单独查询(更灵活可控)
如果你只想在特定页面(比如单文章页)实现分组,或者想给每组评论加标题(比如“订阅者评论”“访客评论”),可以直接在评论模板(通常是comments.php)里替换默认的评论循环,手动查询两组评论并分别输出:
<?php // 第一组:查询并显示订阅者评论 $subscriber_args = array( 'user_id' => get_users(array('role' => 'subscriber', 'fields' => 'ID')), 'orderby' => 'comment_date', 'order' => 'ASC' // 按评论时间正序排列,可改为DESC倒序 ); $subscriber_comments = new WP_Comment_Query($subscriber_args); if ($subscriber_comments->have_comments()) : ?> <h3>订阅者评论</h3> <ol class="comment-list"> <?php wp_list_comments(array('style' => 'ol'), $subscriber_comments->comments); ?> </ol> <?php endif; ?> <?php // 第二组:查询并显示访客评论 $guest_args = array( 'user_id' => 0, 'orderby' => 'comment_date', 'order' => 'ASC' ); $guest_comments = new WP_Comment_Query($guest_args); if ($guest_comments->have_comments()) : ?> <h3>访客评论</h3> <ol class="comment-list"> <?php wp_list_comments(array('style' => 'ol'), $guest_comments->comments); ?> </ol> <?php endif; ?>
这种方法的好处是可以完全自定义每组评论的样式、标题,甚至添加额外的说明文字,自由度更高。
注意事项
- 修改主题文件前,建议先备份文件,或者使用子主题来添加代码,避免主题更新后代码丢失。
- 如果你的网站有其他用户角色(比如编辑、作者),他们的评论会被排除在这两组之外。如果需要包含这些角色,可以调整代码里的
user_id筛选条件,比如把订阅者ID和其他角色ID合并。
内容的提问来源于stack exchange,提问作者kayzoe
相关产品推荐
相关产品推荐

