Search code examples
drupaldrupal-7drupal-routes

Drupal 7 hook_menu for specific content type


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';
}

Solution

  • 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.