开发者

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

开发者 https://www.devze.com 2023-02-04 06:16 出处:网络
So after calling wp_nav_menu like: <?php wp_nav_menu( array(\'menu\' => \'Primary Menu\' )); ?>

So after calling wp_nav_menu like:

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

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-ite开发者_开发知识库m-2 becomes menu-item-store, etc?


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.


Based on @Jeremy answer : I just add sanitize_title() to remove accents and special char.

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

/** for a better wp cleaning take a look @ this gist and include it in your function.php */

0

精彩评论

暂无评论...
验证码 换一张
取 消