php - Wordpress walker call parent walk() method

859

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

However, calling the parentwalk() 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 thewalk() things break.

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

732

Answer

Solution:

Walker::walk will return the string resulting from the walk operation. What you will get is a text that has been created using the methodsWalker::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;
}
750

Answer

Solution:

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

People are also looking for solutions to the problem: php - Decode a string from an array within an array back into an array

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.