How to create simple Walker_Category for WordPress website

WordPress Walkers are very useful solution for custom tree-like data structures. Today i will share simple code for Walker_Category class, which allows you to build custom structure when you call wp_list_categories() function. We know that generally when you call this function it gives you standard ul-li structure which is only customizable its arguments. But if we want to change its tree-like structure, then Walker_Category will help us. So lets say that we want to add some icons before category names. Let’s get started.

1. Let’s add our Walker_Category class to theme’s functions.php

<p>class Walker_Category_Custom extends Walker_Category {</p>
<p>function start_lvl(&amp;$output, $depth=0, $args=array()) {<br />
$output .= &quot;\n&lt;ul&gt;\n&quot;;<br />
<p>function end_lvl(&amp;$output, $depth=0, $args=array()) {<br />
$output .= &quot;&lt;/ul&gt;\n&quot;;<br />
<p>function start_el(&amp;$output, $item, $depth=0, $args=array(),$current_object_id = 0) {<br />
$output.= '&lt;li&gt;&lt;a href=&quot;'.home_url('category/'.$item-&gt;slug).'&quot;&gt;<br />
&lt;img src=&quot;http://some_path_here/images/'.($item-&gt;slug).'.jpg&quot;&gt;<br />
'.esc_attr($item-&gt;name);<br />
//in this case you should create images with names of category slugs<br />
<p>function end_el(&amp;$output, $item, $depth=0, $args=array()) {<br />
$output .= &quot;&lt;/a&gt;&lt;/li&gt;\n&quot;;<br />
}<br />

So, our class is ready. Let’s implement it to our categories menu:

<p>$our_walker= new Walker_Category_Custom();</p>

That’s all. We will get ul-li menu with small icons images before each category name. Something like this:

Screenshot from 2015-05-02 14:12:37

Also with using functions of our class we can build any kind of data-structure for categories menu.

2 comments on “How to create simple Walker_Category for WordPress website

  1. Thank you very much for this. Helped me alot to create a modal form to post from front end. Now i’m trying to use the same modal to edit posts. The only thing i couldn’t acomplish is how to load the categorie list with some categories checked. There’s a way ?

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: