how to display part of a menu tree?

做~自己de王妃 提交于 2019-11-30 15:21:33

You can write a filter_hook to accomplish this.

My method: create an additional start_in argument for wp_nav_menu using my custom hook:

# in functions.php add hook & hook function
add_filter("wp_nav_menu_objects",'my_wp_nav_menu_objects_start_in',10,2);

# filter_hook function to react on start_in argument
function my_wp_nav_menu_objects_start_in( $sorted_menu_items, $args ) {
    if(isset($args->start_in)) {
        $menu_item_parents = array();
        foreach( $sorted_menu_items as $key => $item ) {
            // init menu_item_parents
            if( $item->object_id == (int)$args->start_in ) $menu_item_parents[] = $item->ID;

            if( in_array($item->menu_item_parent, $menu_item_parents) ) {
                // part of sub-tree: keep!
                $menu_item_parents[] = $item->ID;
            } else {
                // not part of sub-tree: away with it!
                unset($sorted_menu_items[$key]);
            }
        }
        return $sorted_menu_items;
    } else {
        return $sorted_menu_items;
    }
}

Next, in your template you just call wp_nav_menu with the additional start_in argument containing the ID of the page you want the children off:

wp_nav_menu( array( 
    'theme_location' => '<name of your menu>',
    'start_in' => $ID_of_page,
    'container' => false,
    'items_wrap' => '%3$s'
) );

I wrote this to print sub-navs of the pages you may be on. If you want to print out the sub-navigation for each of the pages, get the page parent instead of getting the ID. There would be more involved than that, but it's a start.

$menu = wp_get_nav_menu_items( 'Primary Menu' );
$post_ID = get_the_ID();
echo "<ul id='sub-nav'>";
foreach ($menu as $item) {
    if ($post_ID == $item->object_id) { $menu_parent = $item->ID; }
    if (isset($menu_parent) && $item->menu_item_parent == $menu_parent) {
         echo "<li><a href='" . $item->url . "'>". $item->title . "</a></li>";
     }
 }
echo "</ul>";`

Check out wp_list_pages(). It is useful for providing child navigation in the sidebar.

mac joost's answer is great, but I would add that if you want the parent item to print, then you shouldn't unset the parent, so line 18 needs to be adjusted accordingly:

    if($item->object_id != (int)$args->start_in) { unset($sorted_menu_items[$key]); }

have you seen wp_list_pages?

http://codex.wordpress.org/Function_Reference/wp_list_pages

look closer on child_of attribute

You can use Breadcrumb navxt plugin. It does exactly what you are looking for and its really great. Breadcrumb NavXT Pugin

I've stopped to explore how to output custom part of worpress site taxonomy on the server-side. I just use jquery to copy active taxonomy branch from main menu and paste it to the page container I need.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!