Create a taxonomy archive page

WordPress does not offer an archive page for taxonomies from its core. By this I mean a page on which an overview can be found of the terms that fall under this taxonomy.

Let’s say we have a taxonomy called “topic” and want to show these topics on an archive page. Posts with for example post type “questions” can then be placed under these topics.

So for example a taxonomy: “Topic” with underneath a term: “Food” with underneath a Post type: “Question”.

I would approach this as follows:

First add rewrite rules to have the taxonomy in the URL recognized by WordPress.

function add_topic_rewrite_rules() {
   add_rewrite_rule( '^topic/?$', 'index.php?tax_archive=topic','top' );
}
add_action( 'init', 'add_topic_rewrite_rules' );

Add a query var “tax_archive” that we can use to recognize when to load the template for the taxonomy archive page.

function add_topic_query_vars( $vars ) {
   $vars[] = 'tax_archive';
   return $vars;
}
add_action( 'query_vars', 'add_topic_query_vars' );

Finally, we check the query var in the template include hook to load the template “topic-archive.php”.

function tax_archive_template_include( $template ) {
   $tax_archive = get_query_var( 'tax_archive' );
   if ( $tax_archive && 'topic' == $tax_archive ) {
      $template = locate_template( ['topic-archive.php'] );
   }
   return $template;
}
add_action( 'template_include', 'tax_archive_template_include' );

Now you can start creating your tax archive template (topic-archive.php). Keep in mind that of course, you have to create some custom functionality on this page to have the correct terms / categories appear on the page. If you have any questions about this, feel free to ask them in the comments.

I'm Robbert Vermeulen. I document everything I learn and help thousands of people with coding WordPress. My site has no ads or sponsors. If you enjoy my content, please consider supporting what I do.

Comments

    No comments yet..

Leave a reply

Feel free to ask questions or make comments.