0

I am creating a navigation with bootstrap in a custom WP theme. I have managed to get this result:

<li id="menu-item-27" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-27">...</li>

However I have already styled my navigation before transforming it to WP navigation like this:

<li class="" id="nava"><a href="--><?php //echo get_option('home');?><!--/">Home</a></li>

I want to replace id="menu-item-27" with id="nava".

Any help is much appreciated!

1
  • You could try the nav_menu_item_id filter.
    – birgire
    Commented Dec 22, 2015 at 18:14

2 Answers 2

1

You could use the nav_menu_item_id filter like this:

add_filter( 'nav_menu_item_id', function( $menu_id, $item, $args, $depth )
{
    if( 'menu-item-27' === $menu_id )
        $menu_id = 'nava';

    return $menu_id;
}, 10, 4 );

but I this is "unstable" regarding the menu ID, if you delete and re-insert menu items. You might also want to target a specific menu location.

A common method, that I like for it's flexibility, is to check for a specific CSS classes, that we can set within the navigational UI in the backend.

Here's an example where we check for the set-id-nava class. If it is set, then we override the CSS id with nava:

add_filter( 'nav_menu_item_id', function( $menu_id, $item, $args, $depth )
{
    if( in_array( 'set-id-nava', (array) $item->classes ) )
        $menu_id = 'nava';

    return $menu_id;
}, 10, 4 );

We could also make this more dynamically and check for set-id-???.

We could even add an extra input field to set CSS id's for each menu item. But that would require more work.

If you don't want the set-id-nava as a CSS class, then you could remove it, e.g. via the nav_menu_css_class filter.

0

Thank you @birgire I edited the walker class like this:

From: 
$id = apply_filters( 'nav_menu_item_id', 'menu-item-'. $item->ID, $item, $args );
To:
$id = apply_filters( 'nav_menu_item_id', 'nava', $item, $args );
1
  • Please don't edit core files, this will be deleted when you updated. Let me construct an example instead.
    – birgire
    Commented Dec 22, 2015 at 19:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.