欢迎您光临自学哈网,只为分享网络知识教程,供大家学习参考!

「自学哈网」WordPress显示出某篇文章所有评论者的名称

作者 : 自学哈 本文共1172个字,预计阅读时间需要3分钟 2022-11-6 共116人阅读
也想出现在这里? 联系我们

一篇优质的文章,会使得大量的用户进行评论互动,当评论一多,就会让人看得眼花缭乱(有些还有分页功能)。这个时候,我们可以使用一段代码来显示某篇文章的所有评论者。

将以下代码添加到WordPress当前主题的函数模板functions.php里面

代码实现

function get_comment_authors_list( $id = 0, $sep = ', ' ) {$post_id = $id ? $id : get_the_ID();if ( $post_id ) {$comments = get_comments( array('post_id' => $post_id,'status'  => 'approve','type'    => 'comment',) ); $names = array();foreach ( $comments as $comment ) {$name = $comment->comment_author;if ( $comment->user_id ) {$user = get_userdata( $comment->user_id );$name = $user ? $user->display_name : $name;} $arr = explode( ' ', trim( $name ) );if ( ! empty( $arr[0] ) && ! in_array( $arr[0], $names ) ) {$names[] = $arr[0];}}unset( $comments ); $sep = $sep ? $sep : ', ';return implode( $sep, $names );}}  add_shortcode( 'comment_authors_list', 'comment_authors_list_shortcode' ); function comment_authors_list_shortcode( $atts = array() ) {$atts = shortcode_atts( array('post_id'  => 0,'list_sep' => '',), $atts ); return get_comment_authors_list( $atts['post_id'], $atts['list_sep'] );}

使用方法1.查看文章ID为567,下面所有的评论者有哪些

就在你的模板中添加以下代码

<?php echo get_comment_authors_list('123'); ?>

这样就可以显示出所有参与评论的评论者

文章中添加短代码

[comment_authors_list post_id="123" /]

2.调用当前文章所有评论者名称,与上面类似只是去掉其中的文章ID,适合放在文章正文模板中。就在你的模板中添加以下代码

<?php echo get_comment_authors_list(); ?>

在文章中添加短代码:

[comment_authors_list /]

本站声明:
本站所有资源来源于网络,分享目的仅供大家学习和交流!如若本站内容侵犯了原著者的合法权益,可联系邮箱976157886@qq.com进行删除。
自学哈专注于免费提供最新的分享知识、网络教程、网络技术的资源分享平台,好资源不私藏,大家一起分享!

自学哈网 » 「自学哈网」WordPress显示出某篇文章所有评论者的名称
也想出现在这里? 联系我们
© 2022 Theme by - 自学哈网 & WordPress Theme. All rights reserved 浙ICP备2022016594号