When it comes to managing nodes with the menu system, There's always that set of nodes that somehow don't have anywhere to go in the primary menu. So for the current site I'm working on, certain nodes needed a default menu even if they were not a part of the usual primary links displayed on most nodes.

Here's the idea behind what I did,
• first, check the menu_links table to see if there is a row for the current path (i.e. 'node/1')
• then, if there is nothing found, find the path of a default menu we do want to use.
• set the default menu as the current menu item (menu_set_item)

that's it

/**
 * The all powerful preprocess function, so handy.
 * Set the new item here to be sure its ready for rendering.
 */
function mysite_preprocess_node(&$variables) {
  $node = $variables['node'];

  // set default menu if needed.
  _set_default_menu($node->nid);
}

/**
 * For most items some menu is set. But for those that do not
 * we need to set one.  
 */
function _set_default_menu($nid){
  if (!node_has_menu("node/$nid")) {
    $menu = _find_default_menu($nid);
  }
}

// does node have menu
function node_has_menu($path) {
  $sql = "SELECT 'TRUE' FROM drupal_menu_links ";
  $sql .= "WHERE menu_name IN ('primary-links') AND ";
  $sql .= "link_path = '%s'";
  $result = db_result(db_query($sql, $path));
  return $result;
}

/**
 * Here the default menu is found.  You could find your default menu several different ways, 
 * like using a taxonomy already set on the node or any other field set on the node, or even a default
 * variable.
 */
function _find_default_menu($nid) {
  $sql = "SELECT link_path FROM drupal_menu_links WHERE plid = 0 AND ";
  $sql .= "menu_name IN ('primary-links') AND link_title = '%s'";
  $link = db_result(db_query($sql, 'Some Menu'));

  $router_item = menu_get_item($link);
  // do not set if router_item is empty
  if($router_item) {
    menu_set_item("node/$nid", $router_item);
  }
}

Comments

sebastien.gasser’s picture

Hi,

This article helped me last year in Drupal 6. But now with Drupal 7, it does not work! Can someone help me? Thanks a lot.

Here is my code:

function theme_preprocess_node(&$vars) {
	if ($vars['type'] == 'run') {
		$node = $vars['node'];
		_set_default_menu($node->nid);	
	}
}

function _set_default_menu($nid){
	$router_item = menu_get_item('me_all_runs');
	if($router_item) {		
		menu_set_item("node/$nid", $router_item);
	}
}