0

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

2

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.

0

You can do someting like that:

$slug = sanitize_title( $menu_item->title );

However it is not 100% reliable, because -I think- the slug not always (or doesn't have to be) the same as the title.

-1

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

  • 1
    No, that returns the post ID in many cases. Looks like a bug. – fuxia Jan 16 '13 at 13:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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