如何获得drupal中某个父母下面的所有菜单项?

spr*_*man 14 drupal menu

我真的只需要某个菜单项下面第一级的mlid和标题文本.这就是我现在正在做的事情.(它有效,但我怀疑可能有更多的drupal-y方式.):

/**
 * Get all the children menu items below 'Style Guide' and put them in this format:
 * $menu_items[mlid] = 'menu-title'
 * @return array
 */
function mymod_get_menu_items() {
    $tree = menu_tree_all_data('primary-links');
    $branches = $tree['49952 Parent Item 579']['below']; // had to dig for that ugly key
    $menu_items = array();
    foreach ($branches as $menu_item) {
        $menu_items[$menu_item['link']['mlid']] = $menu_item['link']['title'];
    }
    return $menu_items;
}
Run Code Online (Sandbox Code Playgroud)

在那儿?

Ber*_*rst 24

实际上,使用menu_build_tree()可以轻松获取该信息:

// Set $path to the internal Drupal path of the parent or
// to NULL for the current path 
$path = 'node/123';
$parent = menu_link_get_preferred($path);
$parameters = array(
    'active_trail' => array($parent['plid']),
    'only_active_trail' => FALSE,
    'min_depth' => $parent['depth']+1,
    'max_depth' => $parent['depth']+1,
    'conditions' => array('plid' => $parent['mlid']),
  );

$children = menu_build_tree($parent['menu_name'], $parameters);
Run Code Online (Sandbox Code Playgroud)

$children包含您需要的所有信息.menu_build_tree()检查访问或翻译相关的限制,以便您只获得用户真正应该看到的内容.

  • 另一种选择是在调用`menu_link_get_preferred($ path,'menu_name')`时指定菜单然后让你使用`menu_build_tree('menu_name',$ parameters)的子项;`如果一个节点存在于多个菜单中,可能效率更高?也许. (3认同)

Cap*_*iel 17

afaik,没有(我希望我错了).暂时不用挖掘丑陋的键,只需添加一个foreach($ tree),就可以将函数转换为更抽象的辅助函数.然后你可以使用自己的逻辑输出你想要的东西(在这种情况下为mlid).这是我的建议:


/**
 * Get the children of a menu item in a given menu.
 *
 * @param string $title
 *   The title of the parent menu item.
 * @param string $menu
 *   The internal menu name.
 * 
 * @return array
 *   The children of the given parent. 
 */
function MY_MODULE_submenu_tree_all_data($title, $menu = 'primary-links') {
  $tree = menu_tree_all_data($menu);
  foreach ($tree as $branch) {
    if ($branch['link']['title'] == $title) {
      return $branch['below'];
    }
  }
  return array();
}