I would like to build a menu structure where you can only see the menu item of the current page like on this web site http://www.bigspaceship.com/services/
I search around and I have the following function so far
<?php
$menu_items = wp_get_nav_menu_items( 'main-menu' );
foreach( $menu_items as $item ) {
print_r( $item ) ; // see what you can work with
// carry on
}
How can I actually print only the menu item name for the current page?
I want to still control the menu item from the dashboard meaning I want to be able to change the name of each menu within the admin and have them dynamically update.
Thanks for any help.
-
Within each menu item, object_id
holds the ID of whatever object
the menu item refers to. This will be a post / page / CPT / term ID. If it’s a custom link, the ID refers to itself. (If you want to know what type of object it is, object
contains that.)
-
get_queried_object_id()
will give you the ID of the current page.
-
We can use the API function
wp_filter_object_list()
to filter out any menu items where the object_id
doesn’t match the
queried object.
-
We’ll then be left with an array containing a single element, so we
use php’s current
so that $this_item
now contains just the
matching menu item object.
-
and finally, title
holds the name we’ve given the menu item.
$menu_items = wp_get_nav_menu_items( 'main-menu' );
$this_item = current( wp_filter_object_list( $menu_items, array( 'object_id' => get_queried_object_id() ) ) );
echo $this_item->title;
Note- I didn’t test this, so hopefully it works!