【问题标题】:Custom walker decorator自定义步行者装饰器
【发布时间】:2015-04-12 22:46:35
【问题描述】:

我需要在我的菜单中添加文本前的额外图标。所以我阅读了我需要实现自定义 Walker_Nav_Menu 的文档。经过一些分析,我认识到我可以实现我的自定义 walker 符合装饰器模式。我在 php 尤其是 wordpress 方面的经验非常少。我的代码很奇怪。看看吧:

class Walker_nav_menu_Decorator extends Walker_Nav_Menu{
    public $menu;
    public static $index = 0;
    function __construct() {
        $menu = new Walker_Nav_Menu();
    }

    public function start_el( &$output, $item, $depth = 0, $args = array(), $id = 0 ) {
        if($item->title == "Main Menu"){
            $args->before = "TEST";
        }
        echo $index;
        $index+=1;
        parent::start_el($output, $item, $depth, $args, $id);
    }
}

它根本不回显 $index。另外在每个菜单项之前添加额外的“TEST”字样。我应该如何正确操作以及为什么这个版本不起作用?

我的课程在我的 functions.php 文件中,我在这里调用我的菜单:

wp_nav_menu( array( 'theme_location' => 'main_menu', 'container' => 'nav' ,'container_class' => 'menu', 'walker' => new Walker_nav_menu_Decorator() ) );

【问题讨论】:

    标签: php wordpress


    【解决方案1】:

    你的 $index 是静态的,所以不要直接调用它,而是通过

    echo self::$index;
        self::$index+=1;
    

    【讨论】:

      猜你喜欢
      • 2013-02-06
      • 2018-04-11
      • 2020-09-04
      • 1970-01-01
      • 2020-07-11
      • 2018-06-05
      • 2014-06-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多