Back to Top

How to change SubMenu Class using Walker in WordPress

To change SubMenu Class using Walker in WordPress

WordPress has the wp_nav_menu() function which is quite powerful and can take a number of parameters that will allow to control the classes and IDs of html tags, the name of the menu and many more.

In this article, we will check modify submenu class name using the walker in wp_nav_menu. Wp_nav_menu is a WordPress function which is useful to display menus to the frontend.

This function provides many parameters using that you can modify display part of the menu. But it is not enough for a satisfying requirement. Sometimes we want to change the class of inner html section which is not possible using provided parameters so WordPress provided another option is known as Walker Class. You can extend Walker_Nav_Menu class and do modification you want to.

Also Read: To change File/Image Upload Path in WordPress

The walker I’d like to point out here is the wp_nav_menu() function, which looks like this:

wp_nav_menu(  
            array(
                  'menu'     => 'Main Menu', 
                  'walker'   => new CD_Walker_Nav_Menu()
	    )
);

// Change Sub-Menu class name
class CD_Walker_Nav_Menu extends Walker_Nav_Menu {
	function start_lvl( &$output, $depth = 0, $arg = Array() ) {
		$indent = str_repeat( "\t", $depth );
		$output .= "\n$indent
\n" . __('back', 'cd') . "
    "; } function end_lvl( &$output, $depth = 0, $arg = Array() ) { $indent = str_repeat( "\t", $depth ); $output .= "\n$indent
"; } }

Explanation:

Here we have extended the Walker_Nav_Menu class with the new class and in that want to change submenu class name so used two functions start_lvl and end_lvl which will check the depth of menu and replace the class name.

That’s all there is to it! Hope this solution will solve your problem and helpful to you.Stay tuned with creativedev for more information 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Most Popular Posts

What is Predefined Interface in PHP

Posted on 3 years ago

Bhumi

Two years blogiversary

Posted on 5 years ago

Bhumi

The Best E-Commerce Plugins for WordPress

Posted on 6 years ago

Bhumi

Hello world

Updated 5 days ago

Nick Carter

In depth Understanding of Laravel Core

Updated 2 months ago

Bhumi

ECMAScript 6 New Features – 2

Updated 1 year ago

Bhumi

The Reader’s Poll – August 2014

Posted on 4 years ago

Bhumi

The Reader’s Poll – June 2014

Posted on 5 years ago

Bhumi

The Readers’ Poll – May 2014

Posted on 5 years ago

Bhumi