Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding class to li elements in wp_nav_menu

Tags:

wordpress

menu

I have problem with wp_nav_menu in wordpress. I want to make structure of Li elements, where all of them will have class "menu-li". But It doesn't work for me. I have this in function.php file:

register_nav_menus(
array(
'primary-menu' => __( 'Primary Menu' ),
'secondary-menu' => __( 'Secondary Menu' )
));

Then I created Menu in Wordpress admin panel and now I want to add my menu to my theme.

                    <?php

                $defaults = array(
                    'theme_location'  => 'primary-menu',
                    'menu'            => '',
                    'container'       => '',
                    'container_class' => '',
                    'container_id'    => '',
                    'menu_class'      => 'menu-li',
                    'menu_id'         => '',
                    'echo'            => true,
                    'fallback_cb'     => 'wp_page_menu',
                    'before'          => '',
                    'after'           => '',
                    'link_before'     => '',
                    'link_after'      => '',
                    'items_wrap'      => '<ul>%3$s</ul>',
                    'depth'           => 0,
                    'walker'          => ''
                );
                wp_nav_menu( $defaults );
                ?>

It displays all elemnet as li in ul but there is no class "menu-li". How can I add it to all li elements?

like image 560
Roberto Avatar asked Jun 14 '16 22:06

Roberto


2 Answers

The menu_class parameter of wp_nav_menu() controls the class added to the <ul> wrapper element, rather than the individual <li>'s. To add classes to the menu items, you want to use the nav_menu_css_class filter.

Here's how it works (add this to your theme's functions.php file):

add_filter ( 'nav_menu_css_class', 'so_37823371_menu_item_class', 10, 4 );

function so_37823371_menu_item_class ( $classes, $item, $args, $depth ){
  $classes[] = 'menu-li';
  return $classes;
}

This will add the menu-li class to every menu item.

You can also do this conditionally based on the $item, $args etc. passed to this filter if you like.

like image 125
Tim Malone Avatar answered Sep 30 '22 15:09

Tim Malone


If you need add class in custom menu, use next code:

add_filter('nav_menu_css_class','arg_menu_classes',110,3);

function arg_menu_classes($classes, $item, $args) {
    if($args->menu == 'FooterMenu') { // name need menu
        $classes[] = 'col-6 col-sm-6'; // add classes
    }
    return $classes;
}
like image 34
Marina Lebedeva Avatar answered Sep 30 '22 14:09

Marina Lebedeva