How to get the post name (slug) from the item ID when traversing the navbar?

I’m working on a filter for nav menu items, such as

add_filter('wp_get_nav_menu_items','nav_items', 11, 3);
function nav_items($items, $menu, $args) {
    foreach ($items as $item) {
        $slug_1 = get_post_field('post_name', $item->ID);
        $slug_2 = $item->post_name;
        // ...
    }
    return $items;
}

But neither $slug_1 and $slug_2 returns the correct slug.

What is the correct way to get the slug associated to a navbar item?

1 Answer
1

May be duplicate, but I wasn’t able to find the answer. $item->object_id stores the actual post ID:

$slug = get_post_field('post_name', $item->object_id);

Leave a Comment