Drupal 8 How to prevent "Log in/register to post comments" from being displayed to anonymous users

Profile picture for user a.berramou
Azz-eddine BERRAMOU 2 December, 2019

To remove the Log in/Register to post comments link from your content type just for anonymous users:

First, you should remove comment-forbidden link from node links for Anonymous user:

Node comment links

You can do it using hook_preprocess_HOOK.

<?php

/**
 * Implements hook_preprocess_HOOK().
 */
function YOURTHEME_preprocess_links__node(&$variables) {
  if (\Drupal::currentUser()->isAnonymous()) {
    unset($variables['links']['comment-forbidden']);
  }
}

Second, you should remove comment-forbidden from the comment links for Anonymous user:

Comment links

We can do this with the same hook.

<?php

/**
 * Implements hook_preprocess_HOOK().
 */
function YOURTHEME_preprocess_links__comment(&$variables) {
  if (\Drupal::currentUser()->isAnonymous()) {
    unset($variables['links']['comment-forbidden']);
  }
}

 

Note: All the code above should be in YOURTHEME.theme  or YOURMODULE.module.

And That's it, now your anonymous users can only see the comments, without the ability to post one or view the log in / register route.