是的,你可以,
Frontend only
您需要检查每个帖子作者的角色。如果该评论作者的角色不是反对者,则将其从该帖子的评论列表中删除。
然后,如果当前登录的用户也是广告商角色的用户,则只能返回评论。
使用comments_array
过滤我们可以查看贴在帖子上的每条评论。但此过滤器应用于comments\\u模板,因此不会影响后端的access注释。
你可以这样做
add_filter( \'comments_array\' , \'wpse_filter_by_role_frontend\' , 10, 2 );
function wpse_filter_by_role_frontend( $comments, $post_id ){
$current_user = wp_get_current_user(); // retrieve the currently logged in user
// go over each comments for the current post
foreach( $comments as $key => $comment ){
$comment_author = new WP_User( $comment->user_id ); // for each comment get the author user object
// here we say unset the current comment if the role of the comment author is not the same as the role of the logged in user
if( $comment_author->roles[0] != $current_user->roles[0] ){
unset( $comments[$key] );
}
}
// Return the filtered $comments array
return $comments;
}
Frontend and backend
add_action( \'pre_get_comments\' , \'wpse_hide_for_backend\' );
function wpse_hide_for_backend( $comments_query ){
// Hide all for non logged in users
if( !is_user_logged_in() ){
return $comments_query->query_vars[\'comment__in\'] = array(0);
}
$current_user = wp_get_current_user();
// if you don\'t want to apply restrictions to admins
if( $current_user->roles[0] == \'administrator\' ){
return $comments_query;
}
$user_ids = get_users( array(
\'role__in\' => $current_user->roles,
\'fields\' => \'ID\'
) );
$comments_query->query_vars[\'author__in\'] = $user_ids;
}
EDIT
我修改了第二个函数。
看到@birgire的回答,我意识到author_in
查询参数并使用get_users
带查询参数role__in
我们可以在前端和后端都达到预期的效果。
感谢@birgire的灵感:)
EDIT
要允许当前用户在获取评论时扮演更多角色(如添加管理员的评论),只需在
role__in
具有所需的角色
因此函数将变成
add_action( \'pre_get_comments\' , \'wpse_hide_for_backend\' );
function wpse_hide_for_backend( $comments_query ){
// Hide all for non logged in users
if( !is_user_logged_in() ){
return $comments_query->query_vars[\'comment__in\'] = array(0);
}
$current_user = wp_get_current_user();
// if you don\'t want to apply restrictions to admins
if( $current_user->roles[0] == \'administrator\' ){
return $comments_query;
}
$user_ids = get_users( array(
\'role__in\' => array(
\'administrator\',
$current_user->roles[0],
),
\'fields\' => \'ID\'
) );
$comments_query->query_vars[\'author__in\'] = $user_ids;
}
或者(为了便于在本论坛上阅读)
$permitted_roles = array(
\'administrator\',
$current_user->roles[0],
);
$user_ids = get_users( array(
\'role__in\' => $permitted_roles,
\'fields\' => \'ID\'
) );