0

I am using this code below to specify a post template for a specific category in my functions.php file.

function get_custom_cat_template($single_template) {
 global $post;

   if ( in_category( 'ms-conversations' )) {
      $single_template = dirname( __FILE__ ) . '/CUSTOM-POST-BLOG-POST.php';

 }
 return $single_template;

}

add_filter( "single_template", "get_custom_cat_template" ) ; 

The code technically works, however I need to specify about 20 categories for that same post template.

When I copy and paste the code again and again I get this fatal error because I am declaring it twice, but I do not know how to include all of the categories I need.

Fatal error: Cannot redeclare get_custom_cat_template() (previously declared in /home/content/12/9195112/html/wp-hoff-testing/wp-content/themes/dw-focus/functions.php:152) in /home/content/12/9195112/html/wp-hoff-testing/wp-content/themes/dw-focus/functions.php on line 174

Here is a list of all the categories I need for that post template.

ms-conversations, artist-of-the-month, exercise, hiking-for-multiple-sclerosis, msaa, caregiving-msaa, updates, ms-resources, ms-tips-msaa, recipe-of-the-month, stories-to-inspire, well-being, guest-bloggers, ms-publications, videos, multiplesclerosis-net, sharkfest, surveys, swim-for-ms, the-motivator

When I try to use commas or & signs to separate the categories I get further errors, how do I declare multiple categories for this chunk of code?

Thank you.

1

You don't need multiple functions. Use an array with in_category to pass multiple slugs:

if( in_category( array( 'ms-conversations', 'artist-of-the-month' ) ) ){
    // do something
}
  • This worked beautifully! – Gina DiSanto Jun 9 '17 at 16:47
0

This is my final code.

function get_custom_cat_template($single_template) {
 global $post;

   if( in_category( array( 'ms-conversations', 'artist-of-the-month', 'exercise', 'hiking-for-multiple-sclerosis', 'msaa', 'caregiving-msaa', 'updates', 'ms-resources', 'ms-tips-msaa', 'recipe-of-the-month', 'stories-to-inspire', 'well-being', 'guest-bloggers', 'ms-publications', 'videos', 'multiplesclerosis-net', 'sharkfest', 'surveys', 'swim-for-ms', 'the-motivator' ) ) ){
      $single_template = dirname( __FILE__ ) . '/CUSTOM-POST-BLOG-POST.php';

 }
 return $single_template;

}

add_filter( "single_template", "get_custom_cat_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.