I have multiple wordpress template files:
- single-example_1.php
- single-example_2.php
- archiv-example_1.php
- archiv-example_2.php
These are the exactly the same, they are just targeting different custom post types. Because of this I want to combine them into one. I have added this function:
add_filter( 'template_include', function( $template )
{
$my_types = array( 'example_1', 'example_2' );
$post_type = get_post_type();
if ( ! in_array( $post_type, $my_types ) )
return $template;
return get_stylesheet_directory() . '/single-example.php';
});
This “redirects” every single- und archiv- sites to the same template.
How can I redirect the archive pages only to archiv-example and single pages to single-example?
There are two parts to this – you will need to handle the template for both the archive templates as well as the single post templates.
For archives use the
is_post_type_archive($post_types)
function to check and see if the current request is for an archive page of one of the post types you want to return. If it’s a match, return your common archive template.For single posts use the
is_singular($post_types)
function to see if the current request is for a single post of one of the post types you specify. If it’s a match, return the common single post template.In both cases you’ll want to return the
$template
if it isn’t a match in case it was modified by another filter.You’ll be wanting to use
is_post_type_archive($post_type)
to check if the query is being served for an archive page or not.