Disable contextual links for certain elements in Drupal 7

Posted on 19/03/2016

Sometimes the core Contextual Links module can get in your way, or be unnecessary on certain elements. Depending on your theme and workflows, you might want to disable them for certain entities. Unfortunately, the core Contextual Links module does not provide a way to disable them without custom code.

If you don't want to write code, check out my Contextual Hide module. It allows you to hide contextual links for certain entities, such as Nodes, Menus, Blocks and Views.

If you don't want to install another module, I'll explain how to do this through code. What you need to implement is hook_contextual_links_view_alter() in your module. You should place your logic there, and finally remove the links by unsetting the ['#links'] array. Here's the code:

  1. /**
  2.  * Implements hook_contextual_links_view_alter().
  3.  */
  4. function YOUR_MODULE_contextual_links_view_alter(&$element, $items) {
  5.   // Disable contextual links on views.
  6.   if (isset($element['#element']['#views_contextual_links_info'])) {
  7.     unset($element['#links']);
  8.   }
  9.   // Disable contextual links on blocks.
  10.   if (isset($element['#element']['#block'])) {
  11.     unset($element['#links']);
  12.   }
  13.   // Disable contextual links on nodes.
  14.   if (isset($element['#element']['#node'])) {
  15.     unset($element['#links']);
  16.   }
  17. }

Finally, if you don't want to deal with any of the above things, you can do this through CSS. It might not be the "best" solution, but it will be get the job done:

  1. .your-node-selector .contextual-links {
  2.   display: none!important;
  3. }