Adding a default menu for a node with no menu

When it comes to managing nodes with the menu system, there’s always that set of nodes that 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 there were not apart of the usual primary links displayed on most nodes.

When it comes to managing nodes with the menu system, there’s always that set of nodes that 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 there were not apart of the usual primary links displayed on most nodes.

Here’s what I did,
* first, check the menu_links table to see if there is a row for the current path (ie ‘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)

and that’s it

Here’s what I added to my template.php file to get this running.

/**<br> * The all powerful preprocess function, so handy.<br> * Set the new item here to be sure its ready for rendering.<br> <strong>/<br>function mysite_preprocess_node(&$variables) {<br>  $node = $variables['node'];<br><br>  // set default menu if needed.<br>  _set_default_menu($node->nid);<br>}<br><br>/</strong>*<br> * For most items some menu is set. But for those that do not<br> * we need to set one.  <br> <strong>/<br>function _set_default_menu($nid){<br>  if (!node_has_menu("node/$nid")) {<br>    $menu = _find_default_menu($nid);<br>  }<br>}<br><br>// does node have menu<br>function node_has_menu($path) {<br>  $sql = "<span class="caps">SELECT</span> 'TRUE' <span class="caps">FROM</span> drupal_menu_links ";<br>  $sql .= "<span class="caps">WHERE</span> menu_name IN ('primary-links') <span class="caps">AND</span> ";<br>  $sql .= "link_path = '%s'";<br>  $result = db_result(db_query($sql, $path));<br>  return $result;<br>}<br><br>/</strong>*<br> * Here the default menu is found.  You could do find your default menu several different ways, <br> * like using a taxonomy already set on the node or any other field set on the node, or even a default<br> * variable.<br> */<br>function _find_default_menu($nid) {<br>  $sql = "<span class="caps">SELECT</span> link_path <span class="caps">FROM</span> drupal_menu_links <span class="caps">WHERE</span> plid = 0 <span class="caps">AND</span> ";<br>  $sql .= "menu_name IN ('primary-links') <span class="caps">AND</span> link_title = '%s'";<br>  $link = db_result(db_query($sql, 'Some Menu'));<br><br>  $router_item = menu_get_item($link);<br>  menu_set_item("node/$nid", $router_item);<br>}

View code on Drupalbin and on Drupal.org

Eric McKenna