Search code examples
wordpresscustom-post-type

Only default Post Template for different Custom Post Types


On my current projet, I've some CPTs (~9), I would like for a part of them to use a same post template and use an other one for the other part. Until there, it's ok with this piece of code.

<?php 
  /* Template Name: 'Template 1'
   * Template Post Type: cpt1, cpt2, cpt3 */ 
?>

My problem is when I'm creating a new post. I have to choose the template each time...(> screenshot) Not really convenient for my client. A repetitive handling.

Would it be possible to force a default template ? Any ideas ?

Thanks in advance for your time.


Solution

  • You can achieve what you need by setting up custom templates for your CPTs that will conform to the WP template hierarchy, and accessing the common template from within these template files.

    Specifically, for the custom post types which you wish to have common templates, you could use the get_template_part() function within these files to access a common template structure.

    Template Hierarchy

    If you name your template files appropriately, WordPress knows that the template should be used by default for a given custom post type.

    For example, if you name a template file single-product.php, this template will be used for a custom post type registered with the slug product.

    The templates are selected in hierarchically, so if you need to you can even have WordPress display a custom template for a specific slug. The hierarchy for custom post types is:

    1. single-{post-type}-{slug}.php If you have custom post type {post-type} with slug {slug}, this template will be used. otherwise...
    2. single-{post-type}.php If you have a custom post type {post-type} this template will be used.
    3. single.php Otherwise, WP falls back to single.php
    4. singular.php - used if there is no single.php
    5. Finally, if there is no other option WP uses index.php.

    In your case, you might set up the various templates individually for each custom post type, but for the templates that should be the same, reference your common template parts from within these templates.

    For example, if you have custom post types cpt1 and cpt2 which should access the same template, create two templates (single-cpt1.php and single-cpt2.php) and add the following code to both of them:

    <?php get_template_part('templates/content', 'common-cpt'); ?>
    

    You can then add the common template data to a template file named templates/content-common-cpt.php and your problem should be solved.

    References