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;
}