function menu_get_object

You are here

7 menu.inc menu_get_object($type = 'node', $position = 1, $path = NULL)
6 menu.inc menu_get_object($type = 'node', $position = 1, $path = NULL)

Get a loaded object from a router item.

menu_get_object() will provide you the current node on paths like node/5, node/5/revisions/48 etc. menu_get_object('user') will give you the user account on user/5 etc. Note - this function should never be called within a _to_arg function (like user_current_to_arg()) since this may result in an infinite recursion.

Parameters

$type: Type of the object. These appear in hook_menu definitons as %type. Core provides aggregator_feed, aggregator_category, contact, filter_format, forum_term, menu, menu_link, node, taxonomy_vocabulary, user. See the relevant {$type}_load function for more on each. Defaults to node.

$position: The expected position for $type object. For node/%node this is 1, for comment/reply/%node this is 2. Defaults to 1.

$path: See menu_get_item() for more on this. Defaults to the current path.

Related topics

2 calls to menu_get_object()
book_block in modules/book/book.module
Implementation of hook_block().
template_preprocess_page in includes/theme.inc
Process variables for page.tpl.php

File

includes/menu.inc, line 702
API for the Drupal menu system.

Code

function menu_get_object($type = 'node', $position = 1, $path = NULL) {
  $router_item = menu_get_item($path);
  if (isset($router_item['load_functions'][$position]) && !empty($router_item['map'][$position]) && $router_item['load_functions'][$position] == $type . '_load') {
    return $router_item['map'][$position];
  }
}

Comments

This can be used to get the $node object in the 'view' $op of hook_block. See how book_block() uses this function.

Note that the example in the documentation to load users is incorrect. In order to load a user on user/5 you need to do the following

<?php
menu_get_object
('user_uid_optional');
?>

This is because menu_get_object() requires that a function be named as $type . '_load', but the user/%uid page uses user_uid_optional_load() as a load function. The above is a hack, there is an issue to fix this but it will probably be some time until it gets committed and backported.

http://drupal.org/node/595818

Be warned, you cannot use this function to get the node from a View page display with path arguments (e.g. 'node/%/my-view').

See http://drupal.org/node/1236840#comment-4820598 why you can't use this on views.

Another warning, this doesn't work if you do an Ajax call from a node. In my ajax callback, I didn't want to pass the current node id I was on, and used this function to get the current node. But it doesn't work. You'll need to pass the current node id as an argument to the callback, and then do a node_load on the id sent back.