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 use custom menus and I’d like to get the menu item slugs. Is that possible?

// Get the nav menu based on $menu_name (same as 'theme_location' or 'menu' arg to wp_nav_menu)
// This code based on wp_nav_menu's code to get Menu ID from menu slug

$menu_name = 'main-menu';

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);
    $menu_list = '<ul id="menu-' . $menu_name . '">';

        foreach ( (array) $menu_items as $key => $menu_item ) {
            $title = $menu_item->title;
            $url = $menu_item->url;
            $menu_list .= '<li><a href="#' . $url . '">' . $title . '</a></li>';
        }

    $menu_list .= '</ul>';

}

echo $menu_list;

http://codex.wordpress.org/Function_Reference/wp_get_nav_menu_items

share|improve this question
add comment

2 Answers

Well you've Post ID with you. So you can use this custom function to retrieve slug of any post.

function get_the_slug( $id=null ){
    if( empty($id) ):
        global $post;
        if( empty($post) )
            return ''; // No global $post var available.
        $id = $post->ID;
    endif;

    $slug = basename( get_permalink($id) );
    return $slug;
}

This in return will provide you slug of specified post which you can pass as an argument. By default it'll give you slug current post item.

share|improve this answer
add comment

It’s possible to grab the slug with $menu_item->post_name;.

share|improve this answer
    
No, that returns the post ID in many cases. Looks like a bug. –  toscho Jan 16 '13 at 13:35
    
Damn … Thanks for the advice! –  user1706680 Jan 16 '13 at 22:29
add comment

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.