WordPress Custom Walker Tutorial

Posted by Shane

This subject is not very well documented anywhere in the WordPress Codex or online. I only found one site that talked about a custom walker class.

What is a Walker Class?

A walker class allows you to manipulate how data is displaied on your blog without having to modify the core files. What ever methods you do not override use the default method in the Walker class that you Extend.

There are five walkers already built in:

  1. Walker_Comment – Used for when listing comments
  2. Walker_CategoryDropdown – Category list into an HTML dropdown element
  3. Walker_PageDropdown – Page list into an HTML dropdown element
  4. Walker_Page – Page listing widget/navigation
  5. Walker_Category – Category dropdown tree

In this example, I am going to show you how I worked on extending the Walker_Page class and implementing it correctly in a theme.

header.php

$walker_pages = new Walker_Page_Rabbit;
wp_list_pages(array('walker' => $walker_pages, 'title_li' => '', 'depth' => '1'));

functions.php

class Walker_Page_Rabbit extends Walker_Page {
 //... code here ...
}

Within this class you can have methods/function that override WordPress’s default code including how it works and how the information is displayed.  Instead of relying on WordPress to create it and then you format it with CSS you can make it right from the start and make the code more beautiful or do something totally different.

“O.k. I get it. I can override the walker. Why can’t I just use a callback?”

Callbacks are fine. Use callbacks. But if you were to use a walker you can add additional switches that a callback can’t handle allowing you for more customized looks. Not all walkers that WordPress has callbacks.

I have two uses of wp_list_pages. One is for the upper navigation and the other is for subpages (View the About page). Both look the same, but if I added an extra item to the array.. lets say ‘area’ and defined it as subpages and inside my customer walker method ‘start_el’  I can say..

if (subpages)
//... this is the css you are going to use ...
else
//... use this set of css ...

..and the output xhtml code would all still be the same, but be customized based off a new variable.

Using Walker classes does require some knowledge of Object Orientated Programing (OOP) in PHP, but it’s not a total requirement. There are still areas in which do not use a walker class and only filters so there is room for expansion.

One of the uses of a Walker class is that there could be a Walker_Widget class created that can make all widgets, custom or standard follow the same design standard so that widgets instead of outputting their own design use the design stated by a theme’s Walker.

Walker manipulation can be very powerful if used correctly.