Taxonomies are powerful and convenient when used correctly. Let’s dive into the code that actually makes them work — specifically, being able to display what you want as the title of your custom taxonomy page as opposed to the standard “Archives” heading.
For example, we recently put together a website that had a custom post type of “Projects” and that post type had a custom taxonomy of “Status.” This gave the end user the ability to add new projects and filter them into “Current Projects” or “Completed Projects.” The only downside to this was that if you were on the “Current Projects” page, the page title still defaulted to “Archives” – just like WordPress specifies. We wanted to be able to have it automatically pull the taxonomy name without any work on their end even if they decided they wanted to add “Future Projects” taxonomy or something along those lines.
If you hop into your archive.php file, you will most likely see something along the lines of an h1 with a class of “page-title” and PHP code under going through elseif statements, which is how WordPress filters through all of the different types of archives to make sure they are outputting the correct heading. Usually, the code will start like it does below with if is_category, but your theme may take a different approach. The big thing here is to plug the code in after the opening if statement and it should just work from there.
Let’s take a look:
if ( is_category() ) : single_cat_title(); // Use this code elseif ( is_tax('your_custom_taxonomy_slug') ) : // $term = get_term_by( 'slug', get_query_var( 'term' ), get_query_var( 'taxonomy' ) ); echo $term->name; // End of code // Tons of other elseif statements else : _e( 'Archives', 'wetlands' ); endif;
You can see what we added in that little “Use this code” section – short and sweet. All the PHP is saying is “if this is the taxonomy of (‘your_custom_taxonomy_slug’) then get the taxonomy name and print it.” You should be able to copy and paste that bit into the series of elseif statements, replace the ‘your_custom_taxonomy_slug’ with the slug of your taxonomy and you’ll have your taxonomy page title in no time.
This little bit of code made our jobs here at Southern Web much easier and is now used on a pretty regular basis to solve a variety of issues. Do you use any similar techniques? If so, please let us know in the comments.