I have a main navigation and all parents have children.
Eg:
Page A: About Us
child1
child2
Page B : Our services
Child 3
Child 4
I need to include a horizontal sub-menu on a page. But my problem is, if currently we are on page A, all the child items of page A only to be displayed on page.
If we are on Page A, it should looks like:
Page A Child 1 Child 2
Like this, when we go to Page B, the child of page B only to be displayed.
<?php
$args = array(
'theme_location' => '',
'menu' => '13', //nav menu id, which has about-us as a menu.
'container' => 'div',
'container_class' => '',
'container_id' => '',
'menu_class' => 'menu',
'menu_id' => '',
'echo' => true,
'fallback_cb' => 'wp_page_menu',
'before' => '',
'after' => '',
'link_before' => '',
'link_after' => '',
'items_wrap' => '<ul id="%1$s" class="%2$s">%3$s</ul>',
'depth' => 0,
'walker' => ''
);
$menu_items = wp_nav_menu($args);//wp_get_nav_menu_items(13);
I tried writing above code, which resulted in all the parent items with their children.
Can someone help me on this?
In short, I want to get all the children(sub-menu) of About us menu entry.(i.e. I want child1 & child2 as a list with <a>
tags)
Please write this code in theme’s functions.php
Then you can display it in your theme using wp_nav_menu (just like you normally would), but also passing in a sub_menu flag to activate the custom sub_menu function:
When on a page you first get all the pages, then you can get the current page ID, get the children in an array and loop through this array like this:
EDIT: This has nothing to do with the structured menus you make in the backend, it has to do with making a page child of another page directly in the page edit section.
This is doing it all
Thanks for all the solutions !
I wrote a function to help with this, since most examples I found include the page children, but not the parent itself. Just add this function to your
functions.php
file:Then, to use it on a page, simply call it like this:
First thing you need to do is to make your ‘child1’ ‘child2’ pages as child pages of ‘About Us’ page.
Click here to find out more on creating sub pages.
Once you have the pages structured, you can use this function, (link to docs)
Same goes for your ‘Our services’ page, Hope this resolves your problem. Do let us know if you face any problem & welcome to stackoverflow!
A fast and “dirty” solution.
I have created the following file …/wp-content/plugins/gabriel-submenu.php
With this content:
Then in my posts I have:
[gabsubmenu id=93]
Where id is the id of the parent page.
Custom Menu and its Submenus
Find more information and examples at https://developer.wordpress.org/reference/functions/wp_get_nav_menu_items/ .