Drupal - Restrict comments on nodes of a content type based on user role

You can perform a hook_form_alter on the comment form in a custom module. This will allow you to change the form so it checks if the current user has a premium role. If the acting user has the premium role the option to submit a comment is displayed. If they do not show a message like "only premium members can comment".

MODULENAME_form_alter(&$form, &$form_state, $form_id) {
if ( $form_id == 'comment_form') {
  global $user;
   if (!user_role('Premium'){
    // Form alter here to unset comment form and show "only premium members can comment"
    unset($form['author']); 
    unset($form['subject']); 
    unset($form['comment_body']);
    unset($form['actions']['submit'] );
    unset($form['actions']['preview'] );
    print "Only Premium members can comment";
  } 
 }
};

You can look in comment.module for the default code for comments....


The Comment Permissions module might be what you're looking for. Though there is only a Drupal 6 variety. Here is a quote about it (from the module's project page):

... enables control of commenting by user role and by node type. Additional user permissions for selected node types are added to the user access system so you can configure commenting with more control than Drupal core provides.

Note that "reply" links below comments may still appear for users without the permission to add comments. This is unfortunate, but I haven't found a workaround. See https://www.drupal.org/node/185855 for more information. Of course, the links can easily be removed in the theme layer.


Just a clean code to complete the Approved answer above:

/**
 * Implementation of hook_form_alter
 */
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
    // First make sure we are altering the right form       
    if ($form_id == 'comment_form') {
        // Keep the form alter clean by moving the logic to a separate function
        _MYMODULE_restrict_comments($form, $form_state);
    }
}

/**
 * Restrict comments in content type based on user role
 */
function _MYMODULE_restrict_comments(&$form, &$form_state) {
    global $user;
    $node = $form['#node'];
    // a custom function to do your logic
    if (_MYMODULE_comments_should_be_restricted($user, $node)) {
        // unset form elements, you can fetch them easily by print_r(array_keys($form));
        unset($form['comment_body'], $form['actions'], $form['author'], $form['subject']); // etc.
        // add a optional message for user.
        $form['no_access'] = array(
            '#markup' => t('You have no access to comment on this content.')
        );
    }
}

Tags:

Comments

Users