大多数时候,你只需要Walker::walk()
方法,对于此类情况Callback_Walker
可以这样做,允许您为其注册回调。
如果使用闭包和现代PHP版本(>=5.4),您可以获得Closure::bind()
:
class Callback_Walker extends Walker {
private $callback = $callback;
public static function create( $callback ) {
return new self( $callback );
}
public function __construct( $callback, $bindClosure = TRUE ) {
$this->callback = $callback;
if ( $bindClosure and $callback instanceof Closure ) {
Closure::bind( $callback, $this, __CLASS__ )
}
}
function walk( $elements, $max_depth ) {
return $this->callback
? call_user_func( $this->callback, $elements, $max_depth )
: parent::walk( $elements, $max_depth );
}
}
到目前为止,单凭这一点并没有任何作用,但公然复制了@toscho的例子,这就是它的使用方式:
wp_nav_menu(
array (
\'theme_location\' => \'your_theme_location\',
\'walker\' => Callback_Walker::create( function( $elements, $max_depth )
{
$list = array();
foreach ( $elements as $item )
{
$list[] = $item->current
? "<b title=\'You are here\'>{$item->title}</b>"
: "<a href=\'{$item->url}\'>{$item->title}</a>";
}
return join( "\\n", $list );
} ),
\'container\' => \'\',
\'items_wrap\' => \'<p>%3$s</p>\',
\'depth\' => 1
)
);
我希望他能原谅我;)