animisoft
9/7/2017 - 7:55 AM

Assign a custom template to posts that has a certain category (and children).

Assign a custom template to posts that has a certain category (and children).

<?php

add_filter('single_template', 'myfunction_1', 10, 1);
function myfunction_1($single_template) {
  $parent = '{PARENT_CATEGORY_ID}';
  $parent_category_name = 'blog';
  $new_template = 'single-new.php';
  $categories = get_categories('child_of=' . $parent);
  $cat_names  = wp_list_pluck($categories, 'name');

  if (has_category($parent_category_name) || has_category($cat_names)) {
    $single_template = locate_template(array($new_template));
  }

  return $single_template;
}