WordPress步进器调用父级walk()方法

4

当我扩展基础Walker类时,我需要扩展walk()方法。

然而,调用父walk()方法没有任何结果。

以下是我尝试过的方法:

public function walk($elements, $max_depth) {
   parent::walk($elements, $max_depth);
}

public function walk($elements, $max_depth) {
   $parent_class=get_parent_class($this);
   $args = array($elements, $max_depth);

   call_user_func_array(array($parent_class, 'walk'), $args);
}

在我重写walk()方法后,似乎出现了问题。

这个方法应该返回特定的值吗? 我是否需要以不同的方式调用父类方法?


在检查了 WP 核心之后,我发现 walk() 方法返回一些输出,所以你尝试过像这样 return parent::walk($elements, $max_depth); 吗? - thefallen
2个回答

2
< p >Walker::walk会返回遍历操作后的字符串结果。你将获得使用Walker::display_elementWalker::start_lvlWalker::start_el等方法创建的文本。从父类方法中获取的内容已经是HTML代码,可能很难在第二次正确修改,但如果你真的想这样做:

public function walk($elements, $max_depth) {
  $html = parent::walk($elements, $max_depth);

  /* Do something with the HTML output */

  return $html;
}

确实,你是对的,我错过了这一点,因为我期望从核心中针对每个元素调用parent::walk多次。但事实并非如此。 - Alex C

2
正如@TheFallen的评论所指出的,WordPress的类名Walker会返回一个输出。
// Extracted from WordPress\wp-includes\class-wp-walker.php
public function walk( $elements, $max_depth ) {
        $args = array_slice(func_get_args(), 2);
        $output = '';

        //invalid parameter or nothing to walk
        if ( $max_depth < -1 || empty( $elements ) ) {
            return $output;
        }

        ...

如果您想扩展类并覆盖方法,您必须保留原始行为,同时也要返回输出结果。 我的建议:

class Extended_Walker extends Walker {
     public function walk( $elements, $max_depth ) {
         $output = parent::walk($elements, $max_depth);

         // Your code do things with output here...

         return $output;  
     }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接