1

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.

1 Answer 1

7
  1. 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.)

  2. get_queried_object_id() will give you the ID of the current page.

  3. 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.

  4. 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.

  5. 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!

2
  • Comment: It does work
    – Felix
    Jan 20, 2017 at 15:39
  • 2
    What if the current page is an archive?
    – Mithc
    Jul 11, 2018 at 17:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.