Skip to main content

Newsletter

ads

Overriding "Log in or register to post comments" in Drupal 9

This has been a pretty common question in all the Drupal version, and the way to do it has morphed over the last couple of versions.

There are a number of ways to tackle this and I am unsure if I will go back and find others.

 

One way to think of overriding Drupal elements is to do with with a module and use a hook. You also need to know what the underlying array elements of the page.

It helps to know a little about the naming convention of the string containing "Log in or register to post comments". It is associated with the label comment-forbidden.

One you realize this you have a better idea of what you are looking for.

This is going to be ugly as I just wanted to get this down and not worry about formatting my code.

I use this snippet to explore variables in the hook function through print_r.

 if ($uid == 1) {
  $dump = print_r($links, TRUE);
  drupal_set_message(t('<pre>@dump</pre>', array('@dump' => $dump)));

}

And I put it temporarily in the function I am exploring. Once you print the array you can find the element referencing the string "Log in or register to post comments".

 

This is the element you want to override.

//This goes at the top of your .module file before any functions.
use Drupal\node\NodeInterface;


function my_module_node_links_alter(array &$links, NodeInterface $node, array &$context) {


  $uid = \Drupal::currentUser()->id();

  if ($uid == 1) {
  $dump = print_r($links, TRUE);
  drupal_set_message(t('<pre>@dump</pre>', array('@dump' => $dump)));

}

 $links['comment__field_comments']['#links']['comment-forbidden']['title'] = t("boo");


}

 

Now hat I have done here is simply replace the links associated with comment-forbidden with the string "boo". In all reasonable likelihood you will want to add logic to this very similar to what is in the Comment Manager class.

 

I will try to expand on that later.