1

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

1

4 Answers 4

3

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.

0

I've made a solution that gets menus and extracts the slugs from there. I'm not sure if it works perfectly with custom menus, but at least when the menu is using posts, categories, or other possibilities that WordPress offers, it is working.

You can place this function inside your functions.php file and call it anywhere on your theme.

//You need to pass the menu slug as a parameter to the function. 
//Replace $current_menu with the menu slug you want to get the slugs from.
        
function get_menu_slugs( $current_menu ) {
    $slugs_menu = array();
    $array_menu = wp_get_nav_menu_items( $current_menu );

    foreach ( $array_menu as $m ) {
        $single_slug    = basename( $m->url );
        $slugs_menu[]   = $single_slug;
    }
    return $slugs_menu;
}

This function will return one array with the list of slugs extracted from the menu urls.

-1

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

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

Your Answer

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

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