下面的代码添加了用户角色的计数。这篇评论很好地解释了发生的事情。它应该为进一步定制提供一个良好的起点(可能您想隐藏0个计数,更改HTML输出等)。
function comments_shortcode($atts) {
$current_user = wp_get_current_user();
extract( shortcode_atts( array(
\'id\' => \'\'
), $atts ) );
$num = 0;
$post_id = $id;
$queried_post = get_post($post_id);
$cc = $queried_post->comment_count;
if( $cc == $num || $cc > 1 ) : $cc = $cc.\' Comments\';
else : $cc = $cc.\' Comment\';
endif;
$permalink = get_permalink($post_id);
// Get all approved comments for this post.
$args = array(
\'status\' => \'approve\',
\'post_id\' => get_the_id(),
);
$comments = get_comments( $args );
// Get all roles in the system.
// https://developer.wordpress.org/reference/functions/wp_roles/
$all_roles = wp_roles();
// Create an associative array.
// Key is the role name, value holds human readable name and comment count.
$comment_counts = array ();
foreach ( $all_roles->role_names as $role_name => $role_nice_name ) {
$comment_counts[ $role_name ] = array (
\'nice_name\' => $role_nice_name,
\'comment_count\' => 0,
);
}
// Iterate over all comments for this post. Exlude trackbacks, pingbacks, and non-user comments.
foreach ( $comments as $comment ) {
// Exclude trackbacks and pingbacks
if ( \'\' !== $comment->comment_type ) {
continue;
}
if ( 0 === $comment->user_id ) { // Exclude comments from non-users
continue;
} else { // Real user has commented...
$comment_author = get_user_by( \'id\', $comment->user_id );
if ( $comment_author ) {
// Users can be assigned multiple roles, although that is ideally not done in practice.
foreach ( $comment_author->roles as $role ) {
$comment_counts[ $role ][\'comment_count\']++;
}
}
}
}
// Create the HTML output.
$comment_count_output = \'<h3>Comment Counts by Role</h3>\';
$comment_count_output .= \'<ul>\';
foreach ( $comment_counts as $role => $role_data ) {
$comment_count_output .= \'<li><strong>\' . esc_html( $role_data[\'nice_name\'] ) . \'</strong>: <span>\'. esc_html( (string) $role_data[\'comment_count\'] ) . \'</span></li>\';
}
$comment_count_output .= \'</ul>\';
return \'<a href="\'. $permalink . \'" class="comments_link">\' . $cc . \'</a>\' . $comment_count_output;
}
add_shortcode(\'comments\', \'comments_shortcode\');
输出示例:
24 Comments
按角色的评论计数管理员:3编辑:0作者:0贡献者:0订阅者:4客户:0店铺经理:0雇主:0Notes:
评论者不一定是注册用户,因此总评论数并不总是等于每个角色所有评论的总和。
如果用户留下多条评论,则其角色的评论计数将增加。这里没有检查每个用户只统计一条评论,但您可以很容易地添加这条评论。
WordPress技术上允许用户扮演多个角色。这段代码将用于那个不明智的用例。在这些情况下,对于给定的用户,每个指定角色的注释计数对于单个注释将增加1。