In WordPress, a navigation menu, a list of categories or pages, and a list of comments all share one common characteristic: They are thevisual representation of tree-like data structures. This means that a relationship of superordination and subordination exists among the elements of each data tree.
There will be elements that are parents of other elements and, conversely, elements that are children of other elements. A reply to a comment depends logically on its parent, in the same way that a submenu item depends logically on the root element of the tree (or subtree).
Starting with version 2.1, WordPress provides the Walker
abstract class, with the specific function of traversing these tree-like data structures. But an abstract class does not produce any output by itself. It has to be extended with a concrete child class that builds the HTML bricks for specific lists of items. With this precise function, WordPress provides the Walker_Category
class to produce a nested list of categories, the Walker_Page
class, which builds a list of pages, and several other Walker
concrete child classes.
But when we build a WordPress theme, we might need to customize the HTML list’s default structure to fit our particular needs. We may want to add a description to a menu item, add custom class names or perhaps redefine the HTML structure of a list of categories or comments.
Before we begin, let’s look at the most important concept in this article.
Tree-Like Data Structures Link
Wikipedia defines a tree as a hierarchical organization of data:
“A tree data structure can be defined recursively (locally) as a collection of nodes (starting at a root node), where each node is a data structure consisting of a value, together with a list of references to nodes (the ‘children’), with the constraints that no reference is duplicated, and none points to the root.”
So, the structure is characterized by a root element (at the first level), parent elements (which are directly referenced to subordered elements, named children), siblings (which are elements placed at the same hierarchical level) and descendant and ancestor elements (which are connected by more than one parent-child relation).