same template for multiple custom post type single

I know we could use single-custom-post.php But i have multiple custom post type
like

america
nepal
norway

i can do single-america.php , single-nepal.php , single-norway. But they almost have same code basically violating DRY. I am currently registering such post from plugins . How to show the template for them inside plugin with name lets say single-country.php?

I think we can use template_include filter? but i still don’t have idea to do it?

tried like this

add_filter( 'template_include', function ( $template  ) {
    $cpt=["america","nepal","norway"]
    if ( //how to check condition if it is custom post type single ) {
        return ADVANCED_NOTES_DIR . 'country-single.php';
    }
    return $template ;
}) ;

So can we use same template for multiple custom post type single?

thank you 🙂

1 Answer
1

Yes, you can use template_include or the more specific single_template.

Example code:

add_filter( 'single_template', function( $template ) {

  $cpt = [ 'america', 'nepal', 'norway' ];

  return in_array( get_queried_object()->post_type, $cpt, true )
    ? 'path/to/country-single.php'
    : $template;

} );

single_template filter runs only for singular queries, so you don’t need to check you are on a singular view, but just check that the queried post type is one of the CPTs you want to replace the template for.

I used get_queried_object() for the scope.

Leave a Comment