最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

wp query - How to get main menu only with wp_nav_menu

programmeradmin0浏览0评论

I have created one menu and have some sub-menu but I don't want to display any sub-menu from my template.

My Menu code:

<?php wp_nav_menu( array('menu' => 'header-uk', 'menu_id' => 'nav', 'menu_class' => 'sitemap', 'fallback_cb' => false) ); ?>

My Menu Screenshot:

I want to display only this menu in my template:

Awards
Sagres Town
Getting Here
Sister Hotels
Other
Work for Martinhal
Disclaimer
Site Map

I have created one menu and have some sub-menu but I don't want to display any sub-menu from my template.

My Menu code:

<?php wp_nav_menu( array('menu' => 'header-uk', 'menu_id' => 'nav', 'menu_class' => 'sitemap', 'fallback_cb' => false) ); ?>

My Menu Screenshot:

I want to display only this menu in my template:

Awards
Sagres Town
Getting Here
Sister Hotels
Other
Work for Martinhal
Disclaimer
Site Map
Share Improve this question asked May 5, 2014 at 4:33 Mr.HappyMr.Happy 2231 gold badge5 silver badges10 bronze badges
Add a comment  | 

3 Answers 3

Reset to default 1

You can use the depth parameter like this:

wp_nav_menu( array(
    'menu'        => 'header-uk',
    'menu_id'     => 'nav',
    'menu_class'  => 'sitemap',
    'fallback_cb' => false,
    'depth'       => 1,
) );

Or if what you want to do is grab all items to create your own loop/output you can do that as well. Example:

if ( ( $locations = get_nav_menu_locations() ) && isset( $locations[ 'header-uk' ] ) ) {

    $menu = wp_get_nav_menu_object( $locations[ 'header-uk' ] );

    if ( ! empty( $menu ) ) {

        $menu_items = wp_get_nav_menu_items( $menu->term_id );

            if ( $menu_items ) {

                foreach ( $menu_items as $key => $menu_item ) {

                    if ( $menu_item->menu_item_parent == 0 ) {

                        echo '<a href="' . esc_url( $menu_item->url ) . '">' . $menu_item->title . '</a>';

                    }

                }

            }

    }

}

The key is in the menu_item_parent check which makes sure an item isn't a child item before echoing it.

It's a CSS trick, not related to WordPress I guess. BTW you can do something like this:

ul.sitemap{
   list-style-type: none;
   margin: 0;
   padding: 0;
}

ul.sitemap li{
   margin: 0;
   padding: 0;
}

As you've declared the 'menu_class' => 'sitemap' the <ul> will get a class .sitemap that's why we are targeting that class to put our CSS.

You'll need to set the depth parameter in the wp_nav_menu arguments

发布评论

评论列表(0)

  1. 暂无评论