0

I have the following setup:

  • 3 posts: post1, post2, & post3
  • 2 categories: cat1 & cat2
  • 2 templates: singe1.php & single2.php

  • post1 and post2 are assigned to cat1
  • post3 is assigned to cat2

post1 and post2 should use template1 and post3 should use template2

I have found this plugin: https://wordpress.org/plugins/single-post-template/installation/ but it is for every page separate.

Is there any way to relate the post template and the category?

  • Are those post1, post2 and post3 are posts ? or post types ? – CodeMascot Jan 30 '17 at 17:34
  • This question contains code to enable single-category-name.php templates using the single_template filter. – Milo Jan 30 '17 at 17:46
0

You can use the Template Hierarchy to your advantage. In your theme, you can create template files for the different categories, if you'd like.

Let's say you have categories named cats and dogs. If you create a pair of files named category-cats.php and category-dogs.php, those files will be used as the templates for their respective categories.

You can also use the categories' IDs in the template file names. So if cats is category #3 and dogs is category #4, then category-3.php and category-4.php will be used for the respective posts.

References

0

nikolaou,

When I understand you question correct then you want to use different templates based on the categories you're using within your posts, correct?

If that's the case, then you only need one template (single.php) and a combination of get_the_terms() and get_template_part().

<?php

$categories = get_the_terms(get_the_ID(), 'slug');

if ( in_array('cat1', $categories) ) {
    get_template_part('partials/single', '1');
} elseif ( in_array('cat2', $categories) ) {
    get_template_part('partials/single', '2');
}

?>

You should place the code above within The Loop. The two template files are called single-1.php and single-2.php and stored within a folder called partials.

Sources:

0

From your question I'm guessing that you want to assign the template without changing it (or its name). There's a filter for that called single_template. It is used to intercept WP's standard system of finding a template for a post. You would include it in your functions.php like this (untested):

function wpse254523_single_template ($single_template) {
     global $post;
     $cat = get_the_category($post->ID);
     if ($cat == 'cat1' || $cat == 'cat2')
       $single_template = dirname( __FILE__ ) . '/single1.php';
     elseif ($cat == 'cat3')
       $single_template = dirname( __FILE__ ) . '/single2.php';
     return $single_template;
     }

add_filter( 'single_template', 'wpse254523_single_template' );

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.