Is there a template file to list all terms of a given custom taxonomy?

Suppose we registered the composers and the interprets custom taxonomies.

The composers taxonomy could have the following terms:

  • Wolfgang Amadeus Mozart
  • Ludwig van Beethoven
  • Richard Wagner

The interprets taxonomy could have the following terms:

  • Glenn Gould
  • Daniel Barenboim
  • Vienna State Opera

I am wondering whether the WordPress template hierarchy has a special file , like taxonomy-terms.php, to list taxonomy terms with a simple loop:

?php
while ( have_posts() ) : the_post();
    the_title();
endwhile;
?

This would print (assuming the /%postname%/ permalink setting):

  • Wolfgang Amadeus Mozart, Ludwig van Beethoven, Richard Wagner when viewing example.com/composers
  • Glenn Gould, Daniel Barenboim, Vienna State Opera when viewing example.com/interprets

If not, I would like to know the best way to implement this. I would create a page template for each taxonomy, template-composers-terms.php and template-interprets-terms.php and list terms using something like the following code:

?php
/* Template Name: List of composers */ // or 'List of interprets'
$terms = get_terms( 'composers' ); // or get_terms( 'interprets' )
foreach ( $terms as $term ) :
    echo $term-name;
endforeach;
?

Then, I create two pages, "Composers" and "Interprets", to which I respectively assigned the "List of composers" and "List of interprets" templates.

I'm not very comfortable using this method, because it requires creating a new file for each taxonomy.

Topic template-hierarchy custom-taxonomy Wordpress

Category Web


There's an error with the code, I think... as the get_terms support arrays as parameters.
So the best way to do this, I think is:
1- create your template-composers-terms.php
2- Include them in the page using:

<?php get_template_part('template','composers-terms') ?>

and finally in your newly created file put:

<?php
/* Template Name: List of composers or 'List of interprets' */
$terms = get_terms(array(
         'taxonomy' => 'composers', // make sure it is the taxonomy key passed at the  register_taxonomy function.
         'hide_empty' => false
 );
foreach ( $terms as $term ) :
    echo $term->name;
endforeach;
?>

You can include the same file in template-composers-terms.php and template-interprets-terms.php like that :

<?php
/* Template Name: List of composers */

$tax = "composer";
require "include/file_which_does_all_the_work.php";

and if the page slug is the same that the taxonomy slug, you can save the line $tax = ... with that in the included file :

$tax = $GLOBALS["wp_query"]->query["pagename"];

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.