Reputation: 3440
I have multiple wordpress template files:
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?
Upvotes: 1
Views: 2422
Reputation: 27607
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.
add_filter( 'template_include', function( $template ) {
// your custom post types
$my_types = array( 'example_1', 'example_2' );
// is the current request for an archive page of one of your post types?
if ( is_post_type_archive( $my_types ) ){
// if it is return the common archive template
return get_stylesheet_directory() . '/archive-example.php';
} else
// is the current request for a single page of one of your post types?
if ( is_singular( $my_types ) ){
// if it is return the common single template
return get_stylesheet_directory() . '/single-example.php';
} else {
// if not a match, return the $template that was passed in
return $template;
}
});
Upvotes: 3
Reputation: 50787
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.
if ( is_post_type_archive( $post_type ) )
return get_stylesheet_directory() . '/archive-example.php';
return get_stylesheet_directory() . '/single-example.php';
Upvotes: 0