0

I want to modify all of my <li>'s classes and ids, but the function wp_nav_menu() does not let me do so, so I think I need to use a walker. I am pretty new in OO, so using an object is not really easy.

I'm pretty sure I need to extend Walker class (or Walker_Nav_Menu class?), but I'm not sure what method to override/implement. What method of my object is being called when I pass it as an argument in wp_nav_menu( array( 'walker' => new myWalker ) )?

I do not want to do this with filters and actions because I find it cleaner with walkers.

2 Answers 2

0

All of the methods are being overridden when you load your own walker, but typically you would extend another Walker which works a bit like "filtering" or "pluggable functions".

Take a look at this very simple walker from another question:

class my_extended_walker extends Walker_Nav_Menu {
    function start_lvl(&$output, $depth = 0, $args = array()) {
        $output .= "\n<p class=\"sub-menu\">\n";
    }

    function end_lvl(&$output, $depth = 0, $args = array()) {
        $output .= "\n</p>\n";
    }
}

That Walker extends a WordPress Core Walker called Walker_Nav_Menu. There are two methods in that extended walker. Those two overwrite the two methods of the same name in the core Walker. The other methods in Walker_Nav_Menu will be left unchanged.

That is, you can pick and choose which methods to overwrite and you only need to overwrite the ones you need to overwrite. The structure of your class determines what is overwritten, in other words.

2
  • Thank you, but class=\"sub-menu\" is replaced in the code by the default wordpress class and id
    – user25893
    Jul 2, 2013 at 20:23
  • I don't understand the question. That code is from another question and I don't even remember the context. It was only to provide an example of extending the class, nothing more.
    – s_ha_dum
    Jul 2, 2013 at 20:26
0

What i have understand that you want to change the class of all li element to be what you want

try this

class myWalker extends Walker_Nav_Menu {
    function start_lvl(&$output, $depth = 0, $args = array()) {
        $output .= "\n".'<li class="your_custom_class" id ="your_custom_id>'."\n";
    }

    function end_lvl(&$output, $depth = 0, $args = array()) {
        $output .= "\n".'</li>'."\n";
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.