Alex C
Alex C

Reputation: 951

Wordpress walker call parent walk() method

When extending the base Walker class I need to extend the walk() method.

However, calling the parent walk() method yields no results.

These are the approaches I have tried:

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);
}

It appears to me that as soon as I override the walk() things break.

Should this method return some specific value? Should I call the parent method differently?

Upvotes: 4

Views: 682

Answers (2)

Federico J.
Federico J.

Reputation: 15912

As pointed out in a comment by @TheFallen, the class Walker of Wordpress gives back an output

// 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;
        }

        ...

So, if you want to extend the class and overwrite the method, you MUST keep the original behaviour, returning the output too. My suggestion:

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;  
     }
}

Upvotes: 2

Luigi Pressello
Luigi Pressello

Reputation: 935

Walker::walk will return the string resulting from the walk operation. What you will get is a text that has been created using the methods Walker::display_element, Walker::start_lvl, Walker::start_el and so on... What you will get from the parent method is already HTML code probably hard to modify in the right way in a second time, but if you really want to do that:

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

  /* Do something with the HTML output */

  return $html;
}

Upvotes: 2

Related Questions