Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I am trying to get all the IDs in my navigation and convert it to a string so that I can use it with wp_query to get the pages that are only listed in the nav. The code to get the IDs:

$menu_name = 'primary';

if ( ( $locations = get_nav_menu_locations() ) && isset( $locations[ $menu_name ] )) {
    $menu = wp_get_nav_menu_object( $locations[ $menu_name ] );
    $menu_items = wp_get_nav_menu_items($menu->term_id);
}

foreach ( $menu_items as $menu_item ) {
    $numbers[] = $menu_item->ID;
}

$number = implode(',',$numbers);

But it is returning the wrong numbers. When I go to the admin area and hover my mouse over the pages, the number that shows up in the address bar on the bottom of the screen doesn't match. What am I doing wrong?

share|improve this question

2 Answers 2

up vote 5 down vote accepted

Menu items are stored in the posts table with a post_type of nav_menu_item. So, what you are returning is the ID of the menu item itself, not what it points to.

The page/post ID that the menu item refers to is stored in the postmeta table, with a post_id that matches the menu item ID and meta_key = _menu_item_object_id. The easiest way to get the meta_value (ie the page being pointed to by the menu item) is to use something like this:

$numbers[] = get_post_meta( $menu_item->ID, '_menu_item_object_id', true );

share|improve this answer
    
It took me a while to get the code that I posted above to work. I have been trying to add your code in but I have not been able to get it to work. I took out the foreach loop and tried your line above but got nothing. How do I use your example? –  Jamie Apr 6 '13 at 19:34
    
@Jamie Just replace your line: $numbers[] = $menu_item->ID; with the one in my answer. –  anu Apr 6 '13 at 23:16

I have tried this:

$menu_name = 'featured-page';

if ( ( $locations = get_nav_menu_locations() ) && isset( $locations[ $menu_name ] )) {
    $menu = wp_get_nav_menu_object( $locations[ $menu_name ] );
    $menu_items = wp_get_nav_menu_items($menu->term_id);
}

foreach ( $menu_items as $menu_item ) {
    $numbers[] = $menu_item->ID;
}

$numbers[] = get_post_meta( $menu_item->ID, '_menu_item_object_id', true );

echo $numbers;

and just the word "Array" shows up, what am I doing wrong? I am looking for the numbers to be printed out like this.

33,54,34,78

Thanks

share|improve this answer
    
I guess you found out that you can't echo arrays right. –  Mathijs Segers Apr 28 at 18:51

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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