i want restrict my registered authors to write comment to other posts except his own posts. Is it possible? I have no idea how to do it. May be need conditional logic but how?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
I have the same thing running on my website. Here is how I do do it…
Only post author and commentor can view each others comments
function restrict_comments( $comments , $post_id ){
global $post;
$user = wp_get_current_user();
if($post->post_author == $user->ID){
return $comments;
}
foreach($comments as $comment){
if( $comment->user_id == $user->ID || $post->post_author == $comment->user_id ){
if($post->post_author == $comment->user_id){
if($comment->comment_parent > 0){
$parent_comm = get_comment( $comment->comment_parent );
if( $parent_comm->user_id == $user->ID ){
$new_comments_array[] = $comment;
}
}else{
$new_comments_array[] = $comment;
}
}else{
$new_comments_array[] = $comment;
}
}
}
return $new_comments_array; }
add_filter( 'comments_array' , 'restrict_comments' , 10, 2 );
Only allow post author to reply to a comment on their post
add_action( 'pre_comment_on_post', 'wpq_pre_commenting' );
function wpq_pre_commenting( $pid ) {
$parent_id = filter_input( INPUT_POST, 'comment_parent', FILTER_SANITIZE_NUMBER_INT );
$post = get_post( $pid );
$cuid = get_current_user_id();
if( ! is_null( $post ) && $post->post_author == $cuid && 0 == $parent_id ) {
wp_die( 'Sorry, you can only "Reply" to a message - click on the Reply link to send a message to the member who messaged you' );
}
}
I also used a function to add a body class if the user was the current post’s author so I could style the comment form so that the post author could only see the reply comment field…
add_filter(
'body_class',
function( $classes ) {
if ( is_single() ) {
$post = get_queried_object();
$user = wp_get_current_user();
if ( $user->ID == $post->post_author ) {
$classes[] = 'post-author';
}
}
return $classes;
}
);
css
.post-author #respond.comment-respond {display:none;}
.post-author .byuser #respond.comment-respond {display:inline;}
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0