0

I'm working on a major WordPress site and ran into a problem where I need to use multiple custom post types, but I only want to use one template for all of them.

I found a code by Brad Dalton of WPSites that works with a single CPT name. Looking for a solution that allows multiple CPTs. Source: http://wpsites.net/web-design/using-different-custom-single-post-templates/

What I want is the ability to use cpt-1, cpt-2, cpt-3. I'm not a PHP coder, not quite sure how to make this an array that will work in my functions.php

BTW, I wish there was a is_post_type_single like there is a is_post_type_archive. Would be much easier to default to all CPT Single templates.

Editing Reasons: Removed Brad's code to respect his copyright. Added link to source.

  • Link to the source of the code please. – Brad Dalton Oct 15 '14 at 3:48
  • This is clearly a 'do my work for me for free question'. You've done nothing but copy and paste someone else's work. – Brad Dalton Oct 15 '14 at 4:05
  • Considering I searched for 90 minutes, tried to write my own array but failed because I'm not that great of a PHP coder and couldn't find an answer to this topic, I thought others might find this in Google search and find an answer. – Scott Buehler Oct 15 '14 at 4:15
  • Please show your code that you wrote when you tried to write your own array? – Brad Dalton Oct 15 '14 at 4:18
  • Have a look at this post. You should be able to modify the code to work for you – Pieter Goosen Oct 15 '14 at 4:41
1

Doesn't exist any is_post_type_single function, because there is no need for it.

is_singular() fit perfectly your purpose.

Example code using 'template_include' filter:

add_filter( 'template_include', function( $template ) {
  if ( is_singular( array( 'cpt-1', 'cpt-2', 'cpt-3' ) ) ) {
    $locate = locate_template( 'custom-template.php', false, false );
    if ( ! empty( $locate ) ) {
      $template = $locate;
    }
  }
  return $template;
});

Of course change the name of your CPTs and the name of your custom template.

Please note that you haven't to use the full path of template, just its name, but the file need to be in child theme or parent theme folder.

0

Each CPT should have its own templates. If there is common code then you should write it as a function in the functions.php of the theme and call it, or use a different file and include it from all of the single php template, whatever fits your coding style better.

That said, if you think that all your CPTs should be displayed at the same way then you pobably have too many CPTs.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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