Display A Category Checklist In WordPress
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.
Getting A List Of Categories
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:
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>
Gain access to all tutorials
- Premium tutorials covering WordPress, Laravel and VueJS
- Download premium content
- Download premium WordPress plugins
- Only $5 a month
Join the weekly newsletter
Sign up for our newsletter. You'll be updated on new tutorials as they come available.