0

I have a menu like:

-Item1
--Sub1
--Sub2
--Sub3
--Sub4
--Sub5
--Sub6
-Item2
-Item3

and want to do some costum stuff after x subitems, so I have to determine when x is reached. I tried to define a variable in my costum class and then increment it in end_el():

class Walker_Nav_Menu_Costum extends Walker_Nav_Menu {

    var $x = 0;

    function end_el( &$output, $item, $depth = 0, $args = array() ) {

        if ($depth == 1)
        {
            $x++;
        }

        $output .= "<!-- x:".$x."-->";

        $output .= "</li>\n";
    }
}

but unfortunately its always 1 for every element :-/

How would one do this correctly?

1

Inside the function your $x is local.

You might want to use a static variable:

class Walker_Nav_Menu_Costum extends Walker_Nav_Menu {
    static $x = 0;

    function end_el( &$output, $item, $depth = 0, $args = array() )
    {
        if ( 1 == $depth ) self::$x++;
        $output .= "<!-- x:".self::$x."-->";
        $output .= "</li>\n";
    }
}
| improve this answer | |
  • Sure I need a static var, stupid me ... thx :) – christophrus Mar 11 '13 at 14:45
  • You don't necessarily need a static var, you could use a plain object property on the Walker, like $this->x – djb Oct 9 '14 at 13:24
  • @djb True. Apparently, I didn't see the object context when writing my answer. – tfrommen Oct 9 '14 at 22:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.