Trying to manage templates on a blog with lots of custom taxonomies

In my most recent project, I’m dealing with a website that included dozens of custom taxonomies, couple of post types, content, etc. and required different templates for different authors or tags.

Right now, my template folder has about 70 php files for templates, which is really confusing.

I noticed that some themes such as twentyseven manage to store template files in folders and call them in a loop as the following:

get_template_part( 'template-parts/post/content', get_post_format() );

But this is in the loop. My templates are entirely different so i can’t use the above solution, because i will need to use conditionals for altering anything that is not part of the loop.

For example, if i have 3 post types, i have to save 3 template files:

single-type1.php, single-type2.php and single-type3.php.

These templates are entirely different, both in or outside the loop (even different sidebars), so i can’t just make a single.php and call the appropriate post type in the loop.

Is there anyway to address WordPress about custom template files other than just saving it directly inside the theme’s folder?

2 Answers
2

Page templates can be stored within the page-templates or templates subdirectory within a theme, but this does not apply to custom post type or taxonomy templates.

Fortunately, the template_include filter can be used to change the template that will be loaded. In the example below, template files are stored in the /theme-name/templates/ directory.

/**
 * Filters the path of the current template before including it.
 * @param string $template The path of the template to include.
 */
add_filter( 'template_include', 'wpse_template_include' );
function wpse_template_include( $template ) {
    // Handle taxonomy templates.
    $taxonomy = get_query_var( 'taxonomy' );
    if ( is_tax() && $taxonomy ) {
        $file = get_theme_file_path() . '/templates/taxonomy-' . $taxonomy . '.php';
        if ( file_exists( $file ) ) {
            $template = $file;
        }           
    }


    // Handle post type archives and singular templates.
    $post_type = get_post_type();
    if ( ! $post_type ) {
        return $template;
    }

    if ( is_archive() ) {
        $file = get_theme_file_path() . '/templates/archive-' . $post_type . '.php';
        if ( file_exists( $file ) ) {
            $template = $file;
        }
    }

    if ( is_singular() ) {
        $file = get_theme_file_path() . '/templates/single-' . $post_type . '.php';
        if ( file_exists( $file ) ) {
            $template = $file;
        }
    }

    return $template;
}

Leave a Comment