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"),
));
?>
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.