Output a Custom Taxonomy Loop in WordPress

Here is a custom taxonomy loop code snippet, which allows you to output a set of custom taxonomy terms using the get_terms object and a foreach loop.

<?php
// Taxonomy Loop
/**
* Get the Custom Taxonomy
* For a list of other parameters to pass in see link below
* @link https://developer.wordpress.org/reference/classes/wp_term_query/__construct/
* For a list of get_term return values see link below
* @link https://codex.wordpress.org/Function_Reference/get_term
*
*/
$terms = get_terms( array(
'taxonomy' => 'custom_taxonomy_name', // Swap in your custom taxonomy name
'hide_empty' => true,
));
echo '<ul>';
// Loop through all terms with a foreach loop
foreach( $terms as $term ) {
// Use get_term_link to get terms permalink
// USe $term->name to return term name
echo '<li><a href="'. get_term_link( $term ) .'">'. $term->name .'</a></li>';
}
echo '</ul>';
view raw custom-tax.php hosted with ❤ by GitHub

In the above, a custom taxonomy named custom_taxonomy_name is assigned to the variable $terms and then used in a foreach loop to output as a plain html unordered list. One of the parameters passed in is to hide any terms which have no linked posts with the hide_empty value, more parameters can be found at https://developer.wordpress.org/reference/classes/wp_term_query/__construct/

Leave a Comment