12

I tried to add a new tab to a specific content type 'abc', here is the code, but it doesn't work, the tab shows on all the nodes. Can anybody help with it? Thank you!

function addtabexample_menu() {
  $items=array();

  $items['node/%node/test'] = array(
  'title' => 'Test',
  'page callback' => 'handle_test',
  'page arguments' => array('node', 1),
  'access arguments' => array('access content'), 
  'type' => MENU_LOCAL_TASK,
  'weight' => 100,
  );
return $items;
}

function handle_test($node){

  $result='hi';
  if ($node->type == 'abc') {
    $result='I am working';
}
apaderno
  • 28,547
  • 16
  • 75
  • 90
user1480765
  • 177
  • 3
  • 11

1 Answers1

13

The access callback is the right place to make the decision on whether to display the tab, but the code is just a one-liner:

function addtabexample_menu() {
  $items = array();

  $items['node/%node/test'] = array(
    'title' => 'Test',
    'page callback' => 'handle_test',
    'page arguments' => array('node', 1),
    'access callback' => 'addtabexample_access_callback',
    'access arguments' => array(1), 
    'type' => MENU_LOCAL_TASK,
    'weight' => 100,
  );

  return $items;
}

function addtabexample_access_callback($node) {
  return $node->type == 'abc' && user_access('access content');
}

Remember to clear the caches once you've changed the code in hook_menu() for the changes to take effect.

Clive
  • 36,918
  • 8
  • 87
  • 113
  • 2
    Have a look at [hook_admin_paths()](http://api.drupal.org/api/drupal/modules!system!system.api.php/function/hook_admin_paths/7) – Clive Jul 16 '12 at 08:52
  • 1
    As an aside, it's also possible to use a variant of `node_access('view', $node)` in the callback which determines access to the current node for the currently logged in user. – pmagunia Jun 14 '14 at 06:16
  • This is just what I needed to make a page accessible only from two specific products pages, thanks! – Elber CM Jan 21 '21 at 18:03