I create a CPT and turn on Comments. Is it possible to make Comments visible only to a specific role? Only the specific role can make comments when is logged in. For all other roles and visitors, the Comments section will be completely hidden.
Can I make it? Thanks
Hello,
There isn't such kind of built-in feature, it needs custom codes, for example in WordPress default theme 2020, you can try these:
add_filter('comments_open', function($open, $post_id){
$user = wp_get_current_user();
if ( !in_array( 'author', (array) $user->roles ) ) {
//The user has the "author" role
$open = false;
}
return $open;
}, 10, 2);
add_filter('get_comments_number', function($count, $post_id){
$user = wp_get_current_user();
if ( !in_array( 'author', (array) $user->roles ) ) {
//The user has the "author" role
$count = 0;
}
return $count;
}, 10, 2);
Please replace author with your custom user role slug.
More helps:
https://developer.wordpress.org/reference/functions/comments_open/
https://developer.wordpress.org/reference/functions/get_comments_number/
My issue is resolved now. Thank you!
I should modify the question as follows:
Comments visible to a specific role and the post author. The comments to the self should not be hidden.
How to modify the codes?
Thanks again.
What do you mean this:
The comments to the self should not be hidden.
For the question: Comments visible to a specific role and the post author
You can modify the codes as below:
add_filter('comments_open', function($open, $post_id){
$user = wp_get_current_user();
// specific role
if ( !in_array( 'my_role', (array) $user->roles ) ) {
//The user has the "my_role" role
$open = false;
}
// post author
if( get_the_author_meta( 'ID' ) == get_current_user_id() ) {
$open = true;
}
return $open;
}, 10, 2);
add_filter('get_comments_number', function($count, $post_id){
$res = $count;
$user = wp_get_current_user();
if ( !in_array( 'my_role', (array) $user->roles ) ) {
//The user has the "my_role" role
$res = 0;
}
// post author
if( get_the_author_meta( 'ID' ) == get_current_user_id() ) {
$res = $count;
}
return $res;
}, 10, 2);
More help:
https://codex.wordpress.org/Function_Reference/get_the_author_meta
https://developer.wordpress.org/reference/functions/get_current_user_id/
Thanks for your great help. One more thing I would like to trouble you again concerning the comments.
I am trying to use Toolset Layout to create account page for different users (authors). The comments received from the posts are put in the Dashboard=>Comments together. How to let the comments go to the account page automatically based on the same post author?
Are are available shortcodes or custom codes to use? Thanks again.