2

I'm trying to show or hide a menu tab based on whether my node meets a certain condition. In my hook_menu_alter I can't seem to get the $nid even though I was under the impression that the menu_alter fired after node load...

I've been googling for a day now and trying different solutions, but just can't seem to access the $nid.

When I print arg(0) or $_GET['q'] I get the result "admin_menu/flush-cache" instead of "node/62" even though I'm on a node page... what am I missing?

2

Menus are cached; unless you have something funky going on, loading a node won't rebuild that cache (it would be frightfully expensive to do so).

You need to make 'live' decisions in a callback, e.g.

function MYMODULE_menu_alter(&$items) {
  $items['foo']['access callback'] = 'MYMODULE_access_callback';
}

function MYMODULE_access_callback() {
  $node = menu_get_object();
  if ($node && $node->bar) {
    return TRUE; // Allow access.
  }

  return FALSE; // Default for anything that doesn't match your criteria.
}

The above is a contrived example, real-world will be different depending on exactly what you need to do.

  • Seems like there's another way to pass the $nid to the access callback instead of meny_get_object if all you need is the $nid. Add this to the menu $items: $items['foo']['access arguments'] = array(2), and then receive the nid: function MYMODULE_access_callback(nid) { – longboardnode Jul 9 '15 at 13:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.