Scenario: You’ve created a custom taxonomy – a custom category type – probably for your own custom post type. And now you want to list those categories nicely in a tree. Sure, you could use a plugin, but if you’re coding this into a theme or your own plugin then you need to use PHP.
This is actually far easier than I first thought. There are many examples on the web involving complicated nested queries but in fact, WordPress provides an excellent command which makes this all very simple.
Here’s the code:
<?php //list of categories in this archive // $args = array( 'taxonomy' => 'location', 'hierarchical' => true, 'title_li' => '', 'hide_empty' => false, 'child_of' => get_queried_object()->term_id ); $children = get_term_children(get_queried_object()->term_id, 'location'); if (!empty($children)) { ?> <ul class="taxonomylocation"> <?php wp_list_categories( $args ); ?> </ul> <?php } ?>
Just replace ‘location’ with the name of your own taxonomy and it will populate an ordered list for you. There are options you can play with – for example, if you wish to change the default ordering (alphabetical) to something else then have a look at the additional $args parameters you can use here. Also – be sure to change the class=”locationlist” to a class of your choosing – you can use this later to style this list nicely.
Where to add this code?
You should add this code to taxonomy-location.php where you replace location with the slug from your taxonomy. Copy the contents of archive.php or index.php if archive.php doesn’t exist over to taxonomy-location.php and then place the code above wherever you think is suitable – normally after the archive header.
Finally, for the root archive, you can create a new template file and add this code at the top of that template file – then create a new page which uses this template.
- How to create a tree of categories from a custom taxonomy - September 22, 2014
- Managing postcodes and locations with WPAllImport - September 22, 2014
- Why do affiliate merchants reject your website? - August 20, 2014