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
Well you’ve Post ID with you. So you can use this custom function to retrieve slug of any post.
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.
You can do someting like that:
However it is not 100% reliable, because -I think- the slug not always (or doesn’t have to be) the same as the title.
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.
This function will return one array with the list of slugs extracted from the menu urls.
Itâs possible to grab the slug with
$menu_item->post_name;
.