Wordpress Template for Multiple Custom Post Types

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:

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?

2 Answers

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

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';
4

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Alexander Ross
Author

Alexander Ross

Alexander Ross has covered the video game industry for a decade, writing deep dives on game design, esports tournaments, VR developments, and gaming culture.