WordPress template for multiple custom post types

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:

Read More
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?

Related posts

2 comments

  1. 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;
        }
    });
    
  2. 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';
    

Comments are closed.