questions

adding to WordPress menu ID with nav_menu_item_id

Rate this post

I have two nav menus (topbar and main) and I want to add text to the li ID of the topbar menu. How can I prepend text “topbar-” to the li ID, without affecting the main nav menu or any footer menu?

add_filter('nav_menu_item_id', 'topbar_menu_id', 10, 3);
function topbar_menu_id($menu_id, $item, $args) {
    if (!is_admin() && $args->theme_location == 'topbar_menu') {
        $id = apply_filters( 'nav_menu_item_id', 'topbar-menu-item-'. $item->ID, $item, $args );
        $id = $id ? ' id="' . esc_attr( $id ) . '"' : '';

        $output .= $indent . '<li' . $id . $value . $class_names .'>';
    }
}

Thanks in advance

 

✔️Solution:

If topbar_menu is a menu name, then use this code

 add_filter('nav_menu_item_id', 'topbar_menu_id', 10, 3);
 function topbar_menu_id( $menu_id, $item, $args ) {
     if (!is_admin() && $args->menu->name == 'topbar_menu') {
             $menu_id='topbar-'.$menu_id;
     }
         return $menu_id;
 }

else if topbar_menu is a location name, then use this code

add_filter('nav_menu_item_id', 'topbar_menu_id', 10, 3);
 function topbar_menu_id( $menu_id, $item, $args ) {
     if (!is_admin() && $args->theme_location == 'topbar_menu') {
             $menu_id='topbar-'.$menu_id;
     }
         return $menu_id;
 }

Leave a Reply

Your email address will not be published.

Back to top button