Using Walker To Add Menu CSS Class Functionality

I’m trying to add the ability to insert Custom CSS Classes to menu items. I believe I do this by extending the walker_nav_menu but I’m not sure how to call the custom classes.

This seems like such a simple question but I’ve googled and searched here and couldn’t find anything for simply adding the custom classes.

Read More

Right now I just have:

<?php wp_nav_menu( array( 'theme_location' => 'top-menu', 'walker' => new future_walker_class() ) ); ?>

and

class future_walker_class extends Walker_Nav_Menu {
/*not sure what to put here*/
}

P.S. I’m fairly new to PHP/Wordpress. I tried to be as thorough as possible so I don’t waste your time.

Related posts

2 comments

  1. If its a matter of adding icons as per the classes, add it from the back-end and use that class to assign icons through css.

    enter image description here

  2. okay so based on your code it looks to me like you are working with a child theme, or maybe your own theme. — this answer is based on that assumption.

    First things first, you need to register your (new) menu.

    // -- This will go in functions.php
    add_action( 'init', 'register_my_menus' );
    function register_my_menus() {
      register_nav_menus(
        array(
          'menu-1' => __( 'Menu 1' ),
          'menu-2' => __( 'Menu 2' ),
          'menu-3' => __( 'Menu 3' )
        )
      );
    }
    

    You will then need to assign location to the menu in wp-admin > appearance > menus

    Then you can style the custom walker

    // functions.php
    class your_new_Walker_Nav_Menu extends Walker_Nav_Menu {
       function start_lvl(&$output, $depth = 0, $args = Array()) {
            $output .= '<ul class="sub-menu">';
        }
            function end_lvl(&$output, $depth = 0, $args = Array()) {
            $output .= '</ul>';
        }
    }
    

    then when you are ready to call the new menu lets say in header.php

    <!-- header.php -- assuming php is closed at this point -->
        <div class="navbar-header">
        <?php wp_nav_menu(array(
            'theme_location'  => 'menu-1',
       //   'items_wrap'      => 'nav-wrap', un comment if you want 
            'container_class' => 'class1 class2',
            'walker'          => new your_new_Walker_Nav_Menu
        ));
        ?>
        </div>
    

Comments are closed.