0

I have the following code:

$menu = get_term( $locations[$theme_location], 'nav_menu' );
$menu_items = wp_get_nav_menu_items($menu->term_id);

foreach( $menu_items as $menu_item ) {
    $link = $menu_item->url;
    $title = $menu_item->title;
    $slug = $menu_item->post_name;
}

The values of $slug yield page ids instead of the url slugs I'm looking for, except when the $menu_item is a Custom Link instead of a Page. What's more, the actual url has the slug I'm looking for, but page_name contains the same value as the page id.

Example:

echo $link;
>> 'http://localhost:8888/trips/'
echo $title;
>> 'Trips'
echo $slug;
>> 6195 // But I'm looking for 'trips'

I can hack the slug out of the $link, but I figure there has to be a more elegant way to achieve what I'm looking for.

Questions like this one and many others recommend grabbing post_name. What am I missing?

4

Try this :

$menu = get_term( $locations[$theme_location], 'nav_menu' );
$menu_items = wp_get_nav_menu_items($menu->term_id);

foreach( $menu_items as $menu_item ) {
    $link = $menu_item->url;
    $title = $menu_item->title;
    $slug = basename($menu_item->url);
}

Pass the whole permalink to the basename function, which will automatically process the URL and give us only the slug.

  • That was exactly what I was looking for. Thanks! I'd upvote you, but I'm super noob status. – afilbert Dec 13 '16 at 7:32
  • 2
    I modified further, like so: sanitize_title(basename($menu_item->url));. This let me use the $slug as a class name for each menu list item... without worrying about potential garbage from a Custom Link. – afilbert Dec 13 '16 at 7:52

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.