0

I'm trying to add a custom template for all posts in a sub-sub-category. I mean like

Category --> SubCategory Level 1 --> Subcategory Level 2 --> post

I'm using the following code:

 <?php
  $post = $wp_query->post;

  if (cat_is_ancestor_of( 42, $cat ) ) {
      include(TEMPLATEPATH.'/services_template.php');
  } else {
      include(TEMPLATEPATH.'/single-default.php');
  }
?>

However, it only shows a blank page, both in the sub-sub-cat post as well as all teh other posts. I double checked and the templates are there, so I guess there's something wrong with my code, but can't figure what

edit: I have several CPT single pages named single-{CPT-slug}.php . Is it possible this is affecting things?

1
  • Do you debugging turned on? Where have you added this code?
    – ngearing
    Apr 14, 2018 at 3:47

1 Answer 1

1

Instead of include(), use get_template_part()

https://developer.wordpress.org/reference/functions/get_template_part/

<?php $post = $wp_query->post; if (cat_is_ancestor_of( 42, $cat ) ) { get_template_part( 'services', 'template' ) } else { get_template_part( 'single', 'default' ); } ?>

If you create those files and use get_template_part(), then within those files you can set them up to display posts however you see fit. Take a look at the Underscores theme on github, the archive.php file has a good example of using get_template_part() within the loop -

https://github.com/Automattic/_s/blob/master/archive.php

Here is a link as well to one of the template_parts for Underscores to see how they set it up within that file -

https://github.com/Automattic/_s/blob/master/template-parts/content.php

Tom Mcfarlin explains this extremely well here -

https://code.tutsplus.com/articles/how-to-include-and-require-files-and-templates-in-wordpress--wp-26419

Response to your edits: Your single-{CPT-slug}.php templates should not cause any issues with this.

3
  • this doesn't answer the question at all Apr 13, 2018 at 23:48
  • I updated my original comment with the code for this.
    – lavekyl
    Apr 14, 2018 at 3:11
  • Some more details are needed to fully understand and answer this. What file is this code in? Is this a page template, or is this a single-{CPT slug}.php file or an archive-{CPT slug}.php file? Turning on debug mode would also be helpful to help answer this.
    – lavekyl
    Apr 18, 2018 at 15:36

Your Answer

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

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