Support » Developing with WordPress » The expert answers

  • Resolved rfnet

    (@rfnet)


    I need to make a site where a user can post a question and then only specialists (they can be editors) and the same user who wrote the post can reply to that post.
    In brief I need to deny the ability to comment others posts for subscribers.
    Does anybody know how can I achieve this?

Viewing 4 replies - 1 through 4 (of 4 total)
  • Didn’t really test this but looks right. This is using twenty-twentyone them so you might have a different comments layout.

    <?php
    $post_author_id = get_post_field('post_author', get_queried_object_id());
    //echo $post_author_id;
    $user_id = get_current_user_id();
    //echo $user_id;
    $user = wp_get_current_user();
    $allowed_roles = array('editor','whatever-role');
    if( array_intersect($allowed_roles, $user->roles ) || $post_author_id == $user_id ) {
    	comment_form(
    		array(
    			'logged_in_as'       => null,
    			'title_reply'        => esc_html__( 'Leave a comment', 'twentytwentyone' ),
    			'title_reply_before' => '<h2 id="reply-title" class="comment-reply-title">',
    			'title_reply_after'  => '</h2>',
    		)
    	);
    }
    ?>

    Basically get the post author ID and the current user Id. The check if the current user is “whatever role you want to allow” or the post author and if so, show the comment form.

    Note: this just shows or hides the form it self, not the comments made. If you want to do that, just wrap your entire comments form call in the code.

    Thread Starter rfnet

    (@rfnet)

    Hello @tugbucket,
    thanks for your reply. I need to keep wp updates on. Can you advice me on how to use custom code being sure it won’t be deleted by updates?

    If you put it in a child theme, it won’t be overwritten when the parent theme updates.

    Thread Starter rfnet

    (@rfnet)

    Tried it. Seems to do the trick.
    Thanks a lot. You saved my day.

Viewing 4 replies - 1 through 4 (of 4 total)
  • The topic ‘The expert answers’ is closed to new replies.