How can I get a specific item from a wordpress menu? The function wp_nav_menu
returns all items, I want to get for example the second link in the list.
Function:
// HTML5 Blank navigation
function html5blank_nav()
{
wp_nav_menu(
array(
'theme_location' => 'header-menu',
'menu' => '',
'container' => '',
'container_class' => 'menu-{menu slug}-container',
'container_id' => '',
'menu_class' => '',
'menu_id' => '',
'echo' => true,
'fallback_cb' => 'wp_page_menu',
'before' => '',
'after' => '',
'link_before' => '',
'link_after' => '',
'items_wrap' => '<ul class="ul-menu"> %3$s </ul>',
'depth' => 0,
'walker' => ''
)
);
}
Output:
<ul class="ul-menu">
<li><a href="#">menu item 1</a></li>
<li><a href="#">menu item 2</a></li>
<li><a href="#">menu item 3</a></li>
</ul>
Desired output:
<li><a href="#">menu item 2</a></li>
Please Note: this must be a server-side solution, I’m not looking to target menu items through CSS or JavaScript.
Thanks in advance!
Use
wp_get_nav_menu_items($menu, $args)
instead.In your case I believe
should return an array of menu-list objects. You could take the second one and put the content into a list item, or whatever you want to do with it.
https://codex.wordpress.org/Function_Reference/wp_get_nav_menu_items
Nothing new in the logic, but I put the previous solution into a function that returns the output. That makes the code easier to read. You have to put the array of menu items into the function as an argument.
Here’s one way to look at the data: