2

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 :)

2
  • This is basically identical to your other question.
    – Milo
    Commented Dec 4, 2015 at 17:16
  • @Milo thanks but i don't think so ? How do i check whether the post is single custom type post or not? thank you. So for that condiition i made this post .
    – stlawrance
    Commented Dec 5, 2015 at 2:33

1 Answer 1

2

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.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.