How to add Class in <li> using wp_nav_menu() in Wordpress?

WordpressWordpress ThemingWp Nav-WalkerWp Nav-Menu-Item

Wordpress Problem Overview


I am using wp_nav_menu($args) and I want to add my_own_class CSS classname to the <li> element.

I'd like to get the following result:

<li class='my_own_class'><a href=''>Link</a>

How to do that?

Wordpress Solutions


Solution 1 - Wordpress

No need to create custom walker. Just use additional argument and set filter for nav_menu_css_class.

For example:

$args = array(
	'container'		=> '',
	'theme_location'=> 'your-theme-loc',
	'depth'			=> 1,
	'fallback_cb' 	=> false,
	'add_li_class'	=> 'your-class-name1 your-class-name-2'
	);
wp_nav_menu($args);

Notice the new 'add_li_class' argument.

And set the filter on functions.php

function add_additional_class_on_li($classes, $item, $args) {
	if(isset($args->add_li_class)) {
		$classes[] = $args->add_li_class;
	}
    return $classes;
}
add_filter('nav_menu_css_class', 'add_additional_class_on_li', 1, 3);

Solution 2 - Wordpress

You can add a filter for the nav_menu_css_class action in your functions.php file.

Example:

function atg_menu_classes($classes, $item, $args) {
  if($args->theme_location == 'secondary') {
    $classes[] = 'list-inline-item';
  }
  return $classes;
}
add_filter('nav_menu_css_class', 'atg_menu_classes', 1, 3);

Docs: https://developer.wordpress.org/reference/hooks/nav_menu_css_class/

Solution 3 - Wordpress

HERE WordPress add custom class in wp_nav_menu links

OR you can add class <li class='my_own_class'><a href=''>Link</a></li> from admin panel:

  1. Go to YOURSITEURL/wp-admin/nav-menus.php

  2. open SCREEN OPTIONS

  3. make checked CSS CLASSES, then you will see CSS Classes (optional) field in each menu link.

Solution 4 - Wordpress

Adding Class to <li> tag without editing functions.php file:

  1. Go to Appearance -> Menu -> Screen Options -> CSS Classes
  2. You will get CSS Class option enabled in Menu Items Window

enter image description here

Solution 5 - Wordpress

use this filter nav_menu_css_class as shown below

function add_classes_on_li($classes, $item, $args) {
	$classes[] = 'nav-item';
	return $classes;
}
add_filter('nav_menu_css_class','add_classes_on_li',1,3);

UPDATE

To use this filter with specific menu

if ( 'main-menu' === $args->theme_location ) { //replace main-menu with your menu
    $classes[] = "nav-item"; 
}

Solution 6 - Wordpress

How about just using str_replace function, if you just want to "Add Classes":

<?php
    echo str_replace( '<li class="', '<li class="myclass ',
        wp_nav_menu(
            array(
                'theme_location'    => 'main_menu',
                'container'         => false,
                'items_wrap'        => '<ul>%3$s</ul>',
                'depth'             => 1,
                'echo'              => false
            )
        )
    );
?>

Tough it is a quick fix for one-level menus or the menus that you want to add Classes to all of <li> elements and is not recommended for more complex menus

Solution 7 - Wordpress

None of these responses really seem to answer the question. Here's something similar to what I'm utilizing on a site of mine by targeting a menu item by its title/name:

function add_class_to_menu_item($sorted_menu_objects, $args) {
	$theme_location = 'primary_menu';  // Name, ID, or Slug of the target menu location
	$target_menu_title = 'Link';  // Name/Title of the menu item you want to target
	$class_to_add = 'my_own_class';  // Class you want to add
	
	if ($args->theme_location == $theme_location) {
		foreach ($sorted_menu_objects as $key => $menu_object) {
			if ($menu_object->title == $target_menu_title) {
				$menu_object->classes[] = $class_to_add;
				break; // Optional.  Leave if you're only targeting one specific menu item
			}
		}
	}

	return $sorted_menu_objects;
}
add_filter('wp_nav_menu_objects', 'add_class_to_menu_item', 10, 2);

Solution 8 - Wordpress

I added a class to easily implement menu arguments. So you can customize and include in your function like this:

include_once get_template_directory() . DIRECTORY_SEPARATOR . "your-directory" . DIRECTORY_SEPARATOR . "Menu.php";

<?php $menu = (new Menu('your-theme-location'))
            ->setMenuClass('your-menu')
            ->setMenuID('your-menu-id')
            ->setListClass('your-menu-class')
            ->setLinkClass('your-menu-link anchor') ?>
    
            // Print your menu
            <?php $menu->showMenu() ?>
<?php

class Menu
{
    private $args = [
        'theme_location' => '',
        'container' => '',
        'menu_id' => '',
        'menu_class' => '',
        'add_li_class' => '',
        'link_class' => ''
    ];

    public function __construct($themeLocation)
    {
        add_filter('nav_menu_css_class', [$this,'add_additional_class_on_li'], 1, 3);
        add_filter( 'nav_menu_link_attributes', [$this,'add_menu_link_class'], 1, 3 );

        $this->args['theme_location'] = $themeLocation;
    }

    public function wrapWithTag($tagName){
        $this->args['container'] = $tagName;
        return $this;
    }

    public function setMenuID($id)
    {
        $this->args['menu_id'] = $id;
        return $this;
    }

    public function setMenuClass($class)
    {
        $this->args['menu_class'] = $class;
        return $this;
    }

    public function setListClass($class)
    {
        $this->args['add_li_class'] = $class;
        return $this;
    }

    public function setLinkClass($class)
    {
        $this->args['link_class'] = $class;
        return $this;
    }

    public function showMenu()
    {
        return wp_nav_menu($this->args);
    }

    function add_additional_class_on_li($classes, $item, $args) {
        if(isset($args->add_li_class)) {
            $classes[] = $args->add_li_class;
        }
        return $classes;
    }

    function add_menu_link_class( $atts, $item, $args ) {
        if (property_exists($args, 'link_class')) {
            $atts['class'] = $args->link_class;
        }
        return $atts;
    }
}

Solution 9 - Wordpress

<?php
	echo preg_replace( '#<li[^>]+>#', '<li class="col-sm-4">',
			wp_nav_menu(
					array(
						'menu' => $nav_menu, 
						'container'  => false,
						'container_class'   => false,
						'menu_class'        => false,
						'items_wrap'        => '%3$s',
											'depth'             => 1,
											'echo'              => false
							)
					)
			);
?>

Solution 10 - Wordpress

The correct one for me is the Zuan solution. Be aware to add isset to $args->add_li_class , however you got Notice: Undefined property: stdClass::$add_li_class if you haven't set the property in all yours wp_nav_menu() functions.

This is the function that worked for me:

function add_additional_class_on_li($classes, $item, $args) {
	if(isset($args->add_li_class)) {
	  $classes[] = $args->add_li_class;
	}
	return $classes;
}
add_filter('nav_menu_css_class', 'add_additional_class_on_li', 1, 3);

Solution 11 - Wordpress

// Remove translation from Main Menu

function wpdocs_channel_nav_class($classes, $item, $args){
{

if ('primary' === $args->theme_location) {
    $classes[] = "notranslate";
}
    return $classes;
}
add_filter('nav_menu_css_class', 'wpdocs_channel_nav_class', 10, 4);

This is how you easily add the new class to existing class array of you Menu wrapp

Solution 12 - Wordpress

This is how I added the MainMenu of the WordPress and class to li.

<?php
        $defaults = array( 'menu' => 'mainmenu', 
        'container' => false, 
        'fallback_cb' => 'wp_page_menu', 
        'items_wrap' => '<ul class="navbar-nav" id="myTab">%3$s</ul>', 
        'add_li_class'  => 'nav-item',
       'theme_location' => 'mainmenu' );
        wp_nav_menu( $defaults ); ?>
   

Use this code in functions.php

function li_new_class($classes, $item, $args) {
if(isset($args->add_li_class)) {
    $classes[] = $args->add_li_class;
}
return $classes;
}
add_filter('nav_menu_li_class', 'li_new_class', 1, 3);

Solution 13 - Wordpress

This is a very simple way to call "li" calss and "any class" replace easily. Just follow the instructions.

Use this code in the nav area.

<?php
            $consult_menu = wp_nav_menu(array(
                    'theme_location' => 'topmenu',
                    'menu_id' => 'menu',
                    'menu_class' => 'navbar-nav m-auto',
                    'echo' => false
                )
            );
            $consult_menu = str_replace('menu-item', 'nav-item', $consult_menu);
            echo $consult_menu;
            ?>

Then inspect your code on the browser. find wp default class and than replace "str_replace("default_class_here","new_li_class_here",$consult_menu); | Note: $consult_menu here is my theme name, you can use any name here.

Solution 14 - Wordpress

You could simply use wp_nav_menu_items to Filters the HTML list content for navigation menus.

Display nav menu

wp_nav_menu( array(
   'theme_location' => 'parimary',
   'container' => 'ul',
   'menu_class'=> 'nav col-12 col-md-auto mb-2 justify-content-center mb-md-0',
   'add_li_class'  => 'your-class-name1 your-class-name-2',
) );

Menu Registration

function thesportworship_register_menus(){
    register_nav_menus( array(
        'primary'  => __( 'Main Menu', 'thesportworship' ),
    ) );
}
add_action( 'after_setup_theme', 'thesportworship_register_menus', 0 );

Apply filter

function add_additional_class($classes, $item, $args){
    if(isset($args->add_li_class)){
        $classes[] = $args->add_li_class;
    }
    return $classes;
}

add_filter('nav_menu_css_class', 'add_additional_class', 1, 3);

Solution 15 - Wordpress

Answer already given here year ago. you can follow this answer with good explanation.

https://stackoverflow.com/a/52688935/7162602

Thanks

Solution 16 - Wordpress

Without walker menu it's not possible to directly add it. You can, however, add it by javascript.

$('#menu > li').addClass('class_name');

Solution 17 - Wordpress

You can't add a class directly to the LIs very easily, but is there any reason not to target them in a slightly different but equally specific way (by their parent ul)?

You can set the class or ID of the menu with the menu_class and menu_id parameters (affixed to the UL parent of the LIs) and then target the li's via CSS that way, like so:

<?php wp_nav_menu('menu_id=mymenu'); ?>

And for CSS:

ul#mymenu li {
    /* your styles here */
}

Edit: At the time of writing in 2013 this was the easiest way to add it, but updates since then have added the feature to add CSS classes directly in the admin navigation editor. See more recent answers for details.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAyyaz ZafarView Question on Stackoverflow
Solution 1 - WordpressZunanView Answer on Stackoverflow
Solution 2 - WordpressAndres F GarciaView Answer on Stackoverflow
Solution 3 - WordpressRameez SOOMROView Answer on Stackoverflow
Solution 4 - WordpressTruptiView Answer on Stackoverflow
Solution 5 - WordpressRegolithView Answer on Stackoverflow
Solution 6 - WordpressAminView Answer on Stackoverflow
Solution 7 - WordpressMikeView Answer on Stackoverflow
Solution 8 - WordpressLeotrim LotaView Answer on Stackoverflow
Solution 9 - WordpressTamal SarkerView Answer on Stackoverflow
Solution 10 - WordpressRoventeView Answer on Stackoverflow
Solution 11 - WordpressMuhammad FahadView Answer on Stackoverflow
Solution 12 - WordpressAreeb Saeed RajaView Answer on Stackoverflow
Solution 13 - WordpressMuhammad MohibbullahView Answer on Stackoverflow
Solution 14 - WordpressMD SHAYONView Answer on Stackoverflow
Solution 15 - WordpressArman HView Answer on Stackoverflow
Solution 16 - WordpressAtiqur R.View Answer on Stackoverflow
Solution 17 - WordpressEnnuiView Answer on Stackoverflow