1

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.

1 Answer 1

0

It looks like the single quotes are giving you problems.

Replace:

get_template_part( 'templates', '$childcat->slug' ); 

with:

get_template_part( 'templates', $childcat->slug ); 

Note that double quoted strings in PHP can parse variables, not single quotes.

Also check out the curly syntax in the PHP docs in the variable parsing section.

6
  • @joey I think you can also remove cat_is_ancestor
    – mmm
    May 27, 2017 at 19:10
  • Thanks so much for your response, I really appreciate your help :) I tried replacing the single quotes as you suggested but am still getting the white screen due to an error in that code somewhere - the moment I remove the code section the site works fine again?
    – Joey
    May 28, 2017 at 12:32
  • You're welcome. Sounds like a syntax error you got somewhere. You should use the WP_DEBUG on your test install to see what errors come up or check the error log. Check e.g. codex.wordpress.org/Debugging_in_WordPress @Joey
    – birgire
    May 28, 2017 at 12:35
  • You're missing a } in your code snippet - to close the if @Joey
    – birgire
    May 29, 2017 at 8:07
  • Thank you so much for this Birgire - all working perfectly now, thank you :)
    – Joey
    May 29, 2017 at 12:06

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.