When you have a category hierarchy setup on your WordPress site you will be displayed with a list of checkboxes with parent/child indents on the edit post screen. This will allow you to choose the category that you want to assign to the post. In this tutorial we are going to look at how you will create your own checklist just like this which you can use on the front-end of the site or your own options/settings pages so you can use it on your own custom taxonomy.
There is already a function in WordPress that allows you to get a list of categories and display them on the page, this function is wp_list_categories(). This function will return list items of the categories with links to the category page allowing you to display the list like this.
<ul> <?php wp_list_categories('orderby=name'); ?> </ul>
At the moment this will only return list items, but there are a number of parameters that we can pass into this function to change it's behaviour, the important parameter in this tutorial is the walker parameter. The walker parameter allows you define a Walker class that will process the output of the categories. A Walker class will take in the results of the query and will loop through the results to display them in different ways. There are a number of different Walkers available for you to use in WordPress: - Walker_Nav_Menu_Edit
You can use any of these to pass into the walker parameter to render the output in different ways, or you can create your own Walker class by extending the main Walker class in WordPress. In this tutorial the Walker class we are going to use is the Walker_Category_Checklist, passing this in as the walker parameter will output the categories as a list of checkboxes with the parent/child indents.
<?php $args = array( 'taxonomy' => 'custom-taxonomy', 'walker' => new Walker_Category_Checklist ); ?> <ul class="categorychecklist"> <?php wp_list_categories( $args ); ?> </ul>