WordPress Custom Walker

WordPress Walker class helps to parse a formatted result generated by the functions like wp_nav_menu(), wp_list_categories(). WordPress allows creating custom walker class to do changes with these formatted result.

In this tutorial, we are going to see how to make changes in category list displayed by wp_list_categories(). We are creating a custom walker and sending its instance as wp_list_categories() argument. Using this we can walk through the formatted categories and add our own styles.

WordPress Category List

In a previous tutorial, we have seen how to display list of categories using the WordPress function wp_list_categories(). The following code invokes this function by specifying custom walker instance as its argument.

<?php
	$args = array("walker"=>new CustomWalker())
	wp_list_categories($args); 
?>

Custom Category Walker

The code shows the custom category walker class that extends WordPress Walker_Category.

<?php
	class CustomWalker extends Walker_Category {
		function start_el(&$output, $item, $depth=0, $args=array()) {  
			$output .= "\n<li class='list-element'>".esc_attr($item->name);
		}  

		function end_el(&$output, $item, $depth=0, $args=array()) {  
			$output .= "</li>\n";  
		}  
	}  
?>

This class contains two functions start_el() and end_el() will be invoked start of the list element and end of the list element, respectively. In the start_el() we are adding a class attribute to add our own style to the category list.

Other Walker Function

There are another two functions we can use in the walker. These are, start_lvl() and end_lvl() to make changes in <ul> in each level. But this will not be applicable for the outer <ul> tag enclosing all the parent categories in depth 0. So the custom walker class can have,

<?php
	class CustomWalker extends Walker_Category {
		function start_lvl(&$output, $depth=1, $args=array()) {  
			$output .= "\n<ul class=\"level-element\">\n";  
		}  

		function end_lvl(&$output, $depth=0, $args=array()) {  
			$output .= "</ul>\n";  
		}  

	
		function start_el(&$output, $item, $depth=0, $args=array()) {  
			$output .= "\n<li class='list-element'>".esc_attr($item->name);
		}  

		function end_el(&$output, $item, $depth=0, $args=array()) {  
			$output .= "</li>\n";  
		}  
	}  
?>

This Wordpress code tutorial was published on February 11, 2016.

↑ Back to Top