get_template_part based upon post’s category

Question

I have a WordPress website setup with 5 main parent categories each with dozens of child categories

For each WordPress post in single.php, I’d like to load some content based upon each child category slug that the post belongs to.

i.e. if in category “letters > ABC”, get_template_part abc.php

i.e. if in category “letters > ABC” and “numbers > 123”, get_template_part abc.php and 123.php etc

At the moment I’m doing this the long and inefficient way of:

    <?php if (in_category( 'xxx' )) :  get_template_part( 'templates', 'xxx' ); endif;?>
    <?php if (in_category( 'zzz' )) :  get_template_part( 'templates', 'zzz' ); endif;?>

But obviously that’s not practical for large numbers of categories as I’d have about 500 of those in a row, which I presume would slow down the website considerably.

Ideally I’d like to use something like:

<?php foreach ((get_the_category()) as $childcat) {
    if (cat_is_ancestor_of(165, $childcat)) {
      get_template_part( 'templates', '$childcat->slug' ); 
} 
?>

I was wondering where I am going wrong with the above code? My PHP isn’t great – thank you in advance for any help you can offer.

Joey

Edit: Thanks to Birgire (below) the working code is:

<?php foreach ((get_the_category()) as $childcat) {
    if (cat_is_ancestor_of(165, $childcat)) {
      get_template_part( 'templates', $childcat->slug ); 
} }
?>

and change 165 to whatever the parent category ID is.

This will load the template called templates-xxx.php where xxx is the child category slug name.

0
, , Joey 6 years 2017-05-27T05:12:59-05:00 0 Answers 83 views 0

Leave an answer

Browse
Browse