A better Wordpress walker menu

It took a few wasted hours on the walker class before I dumped it for something better.

November 26, 2016 - 3 minute read -
web

I recently took on a project that allowed me to experience the Wordpress walker class first hand. By no means do I consider myself a Wordpress guru, but I feel I have enough understanding to get by.

The Job was split between the front end dev and myself, he would be using bootstrap 4 to get the menus built up, and I would have to get Wordpress to output the HTML to fit his template.

This seems like an easy enough task, until I realized just how logic heavy it is to get the template working. Wordpress uses a class called the Walker class to modify the output of the menus, this makes for a lot more work. Here is thee sample they give you on the Wordpress codex

<?php
class Walker_Quickstart_Menu extends Walker {

    // Tell Walker where to inherit it's parent and id values
    var $db_fields = array(
        'parent' => 'menu_item_parent',
        'id'     => 'db_id'
    );

    /****
     * At the start of each element, output a <li> and <a> tag structure.
     *
     * Note: Menu objects include url and title properties, so we will use those.
     *****/
    function start_el( &$output, $item, $depth = 0, $args = array(), $id = 0 ) {
        $output .= sprintf( "\n<li><a href='%s'%s>%s</a></li>\n",
            $item->url,
            ( $item->object_id === get_the_ID() ) ? ' class="current"' : '',
            $item->title
        );
    }

}
?>

Now unless you are well versed in PHP this could seem a bit much, and you wouldn’t be wrong to feel that way. There have been lots of modern templating language that have made writing code much smoother, and thinking that I had to extend PHP classes to layout a menu didn’t feel right to me.

Enter Timber

Timber became my savior for this project. Timber is a plugin that allows you to write your Wordpress templates in Twig, a modern php templating language.

here is a sample of how you would write a menu in Twig.

<nav>
    <ul class="main-nav">
    {% for item in menu.get_items %}
        <li class="nav-main-item {{item.classes}}"><a class="nav-main-link" href="{{item.link}}">{{item.title}}</a>
            {% if item.get_children %}
            <ul class="nav-drop">
              {% for child in item.get_children %}
                <li class="nav-drop-item"><a href="{{child.link}}">{{child.title}}</a></li>
              {% endfor %}
             </ul>
          {% endif %}
          </li>
   {% endfor %}
   </ul>
</nav>

As you can see Twig just looks like HTML with some variables. Timber allowed me to quickly write up the template for the Menu in a language that was easy to reason with. Now while The extra dependency may feel like a bad thing, it’s nothing compared to the headache I had to deal with when trying to get the walker function to output the correct code.