Make Menus in WordPress use menu-item name instead of number for list item ID?

So after calling wp_nav_menu like:

<?php wp_nav_menu( array('menu' => 'Primary Menu' )); ?>

Read More

I end up with:

<li id="menu-item-1">
<li id="menu-item-2">

ids like menu-item-1, menu-item-2, etc.

Is there some way to replace the numbers with the title of the page instead,so

menu-item-1 becomes menu-item-contact,

menu-item-2 becomes menu-item-store, etc?

Related posts

Leave a Reply

2 comments

  1. You’ll need to filter the ID using WordPress’s nav_menu_item_id filter, which is applied in the nav-menu-template.php file. It takes three arguments, but the second one is what we need to actually get the title of the menu item, and turn it into something useful for the ID attribute. Here’s a function to do that, which works for me in WordPress 3.4.1:

    function custom_nav_menu_item_id($id, $item) {
        $title = sanitize_title_with_dashes($item->title);
        return 'menu-item-'.$title;
    }
    
    add_filter('nav_menu_item_id', 'custom_nav_menu_item_id', 10, 2);
    

    This uses another WordPress function to sanitize the title into a string usable for the ID attribute (or any other HTML attribute).

    Note that this function get’s the menu item’s title, which migth be different than the post or page title if you change it in the Menu panel from the admin.