How To Create Custom Taxonomy Templates

How To Create Custom Taxonomy Templates

Custom taxonomy templates in WordPress allow you to better organize and display content beyond standard categories and tags. Here’s a quick summary of what you’ll learn:

  • What They Are: Special template files that customize how taxonomy pages (like categories or tags) look and function.
  • Why Use Them: Improve content organization, navigation, and SEO while controlling the design for specific taxonomies.
  • How to Create One:
    • Use WordPress’s template hierarchy (e.g., taxonomy-{taxonomy}-{term}.php).
    • Set up a child theme to safely make changes.
    • Write basic or advanced templates using PHP and WordPress functions.
  • Enhancements: Add custom fields, style templates with CSS, or create term-specific layouts.
  • Tools Needed: A code editor, local WordPress setup, and debugging tools like WP_DEBUG.

This guide covers everything from setup to advanced features, helping you create tailored taxonomy templates for your WordPress site.

Custom taxonomies template (3 Solutions!!)

Preparing Your Work Environment

Get your development setup ready to build and test custom taxonomy templates effectively.

Tools You’ll Need

For WordPress development, make sure you have these key tools:

  • Code Editor: Pick one that supports PHP, JavaScript, and HTML. Popular options include Visual Studio Code and Sublime Text.
  • Local Development Environment: Install Local WP as your development server. It’s user-friendly and packed with features [1].
  • Version Control: Use Git to track changes in your template files.

Setting Up a Child Theme

A child theme lets you customize taxonomy templates without changing the parent theme’s core files.

  • Create the Child Theme Directory
    Navigate to wp-content/themes and create a new folder for your child theme (e.g., my-custom-theme) [2].
  • Configure style.css
    In the child theme folder, create a style.css file with the following header:

    /**
     * Theme Name: My Custom Theme
     * Template: parentthemename
     * Version: 1.0
     * Description: Child theme for custom taxonomy templates
     */
    

    Replace parentthemename with the exact name of your parent theme’s folder as it appears in the themes directory [2].

  • Add functions.php
    Create a functions.php file in your child theme folder. Use it to enqueue the parent theme’s styles and add custom functionality. Both the parent and child theme’s functions.php files will load, but the child theme’s file runs first [2].

Enabling WordPress Debug Mode

Debugging helps you spot and fix issues. To enable it, add the following lines to your wp-config.php file [3]:

// Enable WP_DEBUG mode
define( 'WP_DEBUG', true );
// Enable Debug logging
define( 'WP_DEBUG_LOG', true );
// Disable display of errors
define( 'WP_DEBUG_DISPLAY', false );
@ini_set( 'display_errors', 0 );
// Use dev versions of core JS and CSS files
define( 'SCRIPT_DEBUG', true );

"Child themes are extensions of a parent theme. They allow you to modify an existing theme without directly editing that theme’s code." [2]

Once your environment is ready, you’re all set to start building your first taxonomy template in the next section.

Creating Your First Taxonomy Template

Template File Names

WordPress uses a specific structure to locate taxonomy templates. Stick to these naming conventions to ensure compatibility with WordPress’s template hierarchy:

  • taxonomy-{taxonomy}-{term}.php – For individual taxonomy terms.
  • taxonomy-{taxonomy}.php – For taxonomy archive pages.
  • taxonomy.php – A fallback template for all taxonomies.

Once you’ve named your file, add the necessary code as outlined below.

Writing Basic Template Code

Start by creating a new file in your child theme directory, following the naming convention above. Here’s a simple example of a taxonomy archive template:

<?php
get_header();
?>

<main id="primary" class="site-main">
    <?php if ( have_posts() ) : ?>
        <header class="page-header">
            <?php
            $term = get_queried_object();
            echo '<h1 class="page-title">' . esc_html( $term->name ) . '</h1>';

            if ( ! empty( $term->description ) ) {
                echo '<div class="archive-description">' . esc_html( $term->description ) . '</div>';
            }
            ?>
        </header>

        <?php
        while ( have_posts() ) :
            the_post();
            get_template_part( 'template-parts/content', get_post_type() );
        endwhile;

        the_posts_navigation();
    else :
        get_template_part( 'template-parts/content', 'none' );
    endif;
    ?>
</main>

<?php
get_sidebar();
get_footer();

This code ensures your custom taxonomy archive displays the term name, description, and relevant posts.

Testing Your Template

  1. Flush Rewrite Rules
    Navigate to Admin > Settings > Permalinks and click "Save Changes." This step refreshes WordPress’s rewrite rules, ensuring your new template is recognized.
  2. Preview and Verify
    Open your taxonomy archive page through the WordPress admin menu or a taxonomy term link. The URL should look like this:
    https://yoursite.com/taxonomy-name/term-name
  3. Add Debugging Code
    To confirm the correct template is being used, include the snippet below at the very top of your template file:

    <?php
    global $template;
    if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
        echo '<!-- Current template: ' . basename( $template ) . ' -->';
    }
    

    This will display the active template name in the page’s HTML comments when debugging is enabled.

sbb-itb-77ae9a4

Improving Your Template

Working with Taxonomy Data

You can make your template more dynamic by incorporating taxonomy data using WordPress functions. A key function for this is get_queried_object(), which lets you access detailed term data:

<?php $term = get_queried_object(); ?>
<div class="taxonomy-header">
    <h1 class="term-title"><?php echo esc_html($term->name); ?></h1>
    <div class="term-meta">
        <span class="taxonomy-type"><?php echo esc_html($term->taxonomy); ?></span>
        <span class="post-count"><?php echo esc_html($term->count); ?> articles</span>
    </div>
    <?php if ( ! empty( $term->description ) ) : ?>
        <div class="term-description">
            <?php echo wp_kses_post( $term->description ); ?>
        </div>
    <?php endif; ?>
</div>

Once you’ve added the taxonomy data, you can refine its appearance by applying custom styles.

Styling Your Template

To create a polished and consistent look, apply the following CSS rules:

.taxonomy-header {
    margin-bottom: 2rem;
    padding: 1.5rem;
    background: #f8f9fa;
    border-radius: 4px;
}

.term-title {
    margin-bottom: 1rem;
    color: #333;
}

.term-meta {
    font-size: 0.9rem;
    color: #666;
    margin-bottom: 1rem;
}

.term-description {
    line-height: 1.6;
}

These simple styles ensure your template is visually appealing and easy to read.

"Unless I need a template that is radically different from the theme’s archive.php, I tend to stick to adding conditional changes to archive.php." – Josh Pollock, Community Manager for the Pods Framework [4]

Using WP Winners Resources

WP Winners

If you’re looking to go further with customizations, WP Winners is a great resource. They offer tutorials and guides on topics like custom fields, template hierarchy, and optimizing database queries. Some of the areas you can explore include:

  • Adding custom fields and improving template hierarchy
  • Making database queries more efficient for taxonomy pages
  • Using WordPress hooks and filters to enhance template functionality

These resources can help you take your taxonomy templates to the next level.

Advanced Template Features

Building on basic taxonomy templates, these advanced techniques allow for more customization and control over your designs.

Adding Custom Fields

You can expand your taxonomy templates by incorporating custom fields. A popular tool for this is Advanced Custom Fields (ACF). Here’s how you can use ACF to add custom fields to your taxonomy templates:

<?php
$term = get_queried_object();

// Display a custom image field
$term_image = get_field('category_image', $term);
if ($term_image) {
    echo '<div class="term-image">';
    echo wp_get_attachment_image($term_image['ID'], 'full');
    echo '</div>';
}

// Display a custom color field
$term_color = get_field('category_color', $term);
if ($term_color) {
    echo '<div class="term-header" style="background-color: ' . esc_attr($term_color) . ';">';
    echo '<h1>' . esc_html($term->name) . '</h1>';
    echo '</div>';
}
?>

Prefer native WordPress functions? Here’s an example using get_term_meta:

<?php
$featured = get_term_meta($term->term_id, 'featured_category', true);
if ($featured) {
    echo '<span class="featured-badge">Featured</span>';
}
?>

Single Term Templates

To create a custom template for a specific taxonomy term, you can define a dedicated template file. For instance, here’s a template for a product category like "Electronics":

<?php
/* Template Name: Electronics Category
 * Template Post Type: taxonomy-product-category-electronics */

get_header();

$term = get_queried_object(); ?>

<div class="electronics-grid">
    <?php if (have_posts()) :
        while (have_posts()) :
            the_post();
            get_template_part('template-parts/content', 'electronics');
        endwhile;
    endif; ?>
</div>

<?php get_footer(); ?>

This approach allows you to tailor the layout and style specifically for that term.

Theme Customizer Options

You can also add options to the WordPress Customizer to give users more control over taxonomy templates. Here’s an example of adding a setting for "Posts per taxonomy page":

<?php
function add_taxonomy_template_options($wp_customize) {
    $wp_customize->add_section('taxonomy_display_options', array(
        'title' => 'Taxonomy Template Options',
        'priority' => 30,
    ));

    $wp_customize->add_setting('taxonomy_posts_per_page', array(
        'default'           => '12',
        'sanitize_callback' => 'absint',
    ));

    $wp_customize->add_control('taxonomy_posts_per_page', array(
        'label'   => 'Posts per taxonomy page',
        'section' => 'taxonomy_display_options',
        'type'    => 'number',
    ));
}
add_action('customize_register', 'add_taxonomy_template_options');

// Implementation in taxonomy templates
$posts_per_page = get_theme_mod('taxonomy_posts_per_page', 12);
query_posts(array(
    'posts_per_page' => $posts_per_page,
    'tax_query' => array(
        array(
            'taxonomy' => $term->taxonomy,
            'field' => 'term_id',
            'terms' => $term->term_id,
        )
    )
));
?>

This method allows users to adjust the number of posts displayed per page directly from the Customizer. It’s a flexible way to make your templates more user-friendly.

Summary

Quick Steps Overview

Here’s a streamlined look at the main steps:

  • Environment Setup

    • Install the required development tools.
    • Configure a child theme for safe modifications.
    • Turn on WordPress debug mode to catch errors.
  • Template Creation

    • Pick the right template file names (e.g., taxonomy-{taxonomy}-{term}.php).
    • Use an existing template as a starting point.
    • Build a simple template structure to begin with.
  • Template Improvements

    • Add custom fields to expand functionality.
    • Create specific templates for individual terms.
    • Include theme customizer options for better control.

These steps lay the groundwork for further customizations and optimizations.

Next Steps

Take your project further with these advanced techniques:

  • Customization
    Use conditional tags for precise changes. As Josh Pollock explains:

    "Unless I need a template that is radically different from the theme’s archive.php, I tend to stick to adding conditional changes to archive.php." [4]

  • Improving Performance
    Apply the pre_get_posts filter to fine-tune taxonomy queries and keep your code efficient.
  • Additional Learning
    Explore advanced WordPress development guides on WP Winners.
Template Type Use Case Example Implementation
Basic Taxonomy General category display taxonomy.php
Term-Specific Custom layout for specific terms taxonomy-product-electronics.php
Custom Field Enhanced Advanced data display with ACF taxonomy-location.php with ACF integration

Related posts

More WorDPRESS Tips, tutorials and Guides