List Hierarchical Custom Taxonomy Terms for a Post in an Unordered List
You’ve got a custom taxonomy on your WordPress site, and you want to list the terms that apply to a particular post hierarchically (ie, with child terms nested beneath their parent terms). Something like this:
- Parent Term 1
- Child Term 1
- Child Term 2
- Parent Term 2
- Child Term A
- Child Term B
function list_hierarchical_terms() {
global $post;
$taxonomy = 'YOUR_TAXONOMY'; // change this to your taxonomy
$terms = wp_get_post_terms( $post->ID, $taxonomy, array( "fields" => "ids" ) );
if( $terms ) {
echo '<?ul>';
$terms = trim( implode( ',', (array) $terms ), ' ,' );
wp_list_categories( 'title_li=&taxonomy=' . $taxonomy . '&include=' . $terms );
echo '<?/ul>';
}
}
Then you can just use this anywhere you’d like in your theme:
<?php list_hierarchical_terms(); ?>
Up Next: WordPress Ipsum