3

Is there any way to pass a parameter to a menu walker? I'm trying to write a BEM-style walker, and I'd like to be able to pass a class to apply to the menu links via the walker. Something like:

<?php
wp_nav_menu(array(
    "container"      => false,
    "depth"          => 3,
    "items_wrap"     => "%3\$s",
    "theme_location" => "primary",
    "walker"         => new BEMwalker("mobile"),
));
?>
3
  • Can you access the menu args from the walker? Just had a quick read through the docs and it might be possible...? If so, you could add a custom argument
    – Tim Malone
    May 5, 2016 at 22:11
  • 1
    Alternatively you can use a filter to modify the menu links directly, it's wp_nav_menu_items or similar. The $args are then definitely available in there.
    – Tim Malone
    May 5, 2016 at 22:12
  • 2
    You are doing it right already. Just change the constructor to keep that value in a private member.
    – fuxia
    May 5, 2016 at 22:52

1 Answer 1

4

As @toscho said, you can call the walker class with parameters as you did:

new BEMwalker( 'mobile' )

The constructor of BEMwalker will take the arguments (like any other function or method in PHP) so you can access the parameter(s) via $this:

class BEMwalker extends Walker_Nav_Menu {

    private $classes;

    public function __construct( $classes = '' ) {
        $this->classes = $classes;
    }

    public function start_el( &$output, $item, $depth = 0, $args = array(), $id = 0 ) {
       $output .= sprintf( "<li class=\"%s\"><a href=\"%s\">%s</a></li>",
            $this->classes,
            $item->url,
            $item->title
        );
    }

}

Further reading: There's also a GitHub repository called WordPress BEM Menu which might help you to implement a BEM-like syntax.

1
  • 1
    Thanks much! I'm not the best with PHP, but I figured the answer would be this simple :) I'll give this a shot on Monday. May 8, 2016 at 16:36

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.