Custom nav walker: How to acces the $args parameter?

I am creating a custom nav walker. I noticed that the nav walker class from the WordPress core is written rather rough – much of the stuff going on could be spread out through various methods, so I wanted to give that a try.

Currently I am wondering how I can get the $args (containing arguments passed to different methods) parameter in my constructor?

Giving it a close look, there is the filter wp_nav_menu_args (source) that could be used for it like in the following example snippet, but I am wondering if there might be another way to get it:

 class My_Custom_Walker extends Walker_Nav_Menu {

    public function __construct() {
        $args = add_action('wp_nav_menu_args', array($this, 'get_the_args'));
    }

    public function get_the_args($args) {
        return $args;
    }

    […]

A few lines above the filter, there is probably the first occurrence of $args, but is it really written in a way that I can only access it using the filter?

Topic wp-parse-args walker filters Wordpress

Category Web


WordPress Walkers aren't using constructors. They are started up with walk() method which is passed arguments as third argument (confusingly not reflected in method signature).

You can capture it into your object's property with something like this:

class Args_Walker extends Walker {

    public function walk( $elements, $max_depth ) {

        // we could declare above, but would get incompatible signature
        $args = func_get_arg(2);

        $this->args = $args;

        return parent::walk( $elements, $max_depth, $args );
    }
}

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.