2010-06-25 5 views
13

기본 템플릿 계층 구조 동작을 변경하고 자체 카테고리 템플릿 파일이없는 모든 하위 카테고리 레벨 페이지가 상위 카테고리 템플릿 파일을 참조하도록합니다. 내 다른 게시물, Richard M. gave an excellent answer 개별 하위 범주에 대한 문제를 해결했다. 누구든지 그것을 추상화하는 방법을 알고 있습니까?* * * WordPress 카테고리가 상위 카테고리 템플릿을 사용합니다.

function myTemplateSelect() 
{ 
    if (is_category()) { 
     if (is_category(get_cat_id('projects')) || cat_is_ancestor_of(get_cat_id('projects'), get_query_var('cat'))) { 
      load_template(TEMPLATEPATH . '/category-projects.php'); 
      exit; 
     } 
    } 
} 

add_action('template_redirect', 'myTemplateSelect'); 

미리 감사드립니다.

답변

20
/** 
* Iterate up current category hierarchy until a template is found. 
* 
* @link http://stackoverflow.com/a/3120150/247223 
*/ 
function so_3119961_load_cat_parent_template($template) { 
    if (basename($template) === 'category.php') { // No custom template for this specific term, let's find it's parent 
     $term = get_queried_object(); 

     while ($term->parent) { 
      $term = get_category($term->parent); 

      if (! $term || is_wp_error($term)) 
       break; // No valid parent 

      if ($_template = locate_template("category-{$term->slug}.php")) { 
       // Found ya! Let's override $template and get outta here 
       $template = $_template; 
       break; 
      } 
     } 
    } 

    return $template; 
} 

add_filter('category_template', 'so_3119961_load_cat_parent_template'); 

이 경우 즉시 템플릿이 발견 될 때까지 상위 계층 구조가 반복됩니다.

+0

방금 ​​시도했지만 작동하지 못했습니다. 그것을 다시 확인해 주시겠습니까? – Matrym

+2

'TEMPLATE_PATH'보다는 TEMPLATEPATH' –

+0

좋은 점 - updated : – TheDeadMedic

2

부모 테마 폴더에서 보이는 TEMPLATEPATH 변수가 하위 테마에서 작동하지 않을 수 있습니다. 대신 STYLESHEETPATH를 사용하십시오. 예 :

$template = STYLESHEETPATH . "/category-{$cat->slug}.php"; 
3

저는 어떻게 계층 적 분류를 위해 동일한 작업을 수행하는지 궁금합니다. TheDeadMedic의 대답은이 경우에도 약간의 개조로 작동합니다.

function load_tax_parent_template() { 
    global $wp_query; 

    if (!$wp_query->is_tax) 
     return true; // saves a bit of nesting 

    // get current category object 
    $tax = $wp_query->get_queried_object(); 

    // trace back the parent hierarchy and locate a template 
    while ($tax && !is_wp_error($tax)) { 
     $template = STYLESHEETPATH . "/taxonomy-{$tax->slug}.php"; 

     if (file_exists($template)) { 
      load_template($template); 
      exit; 
     } 

     $tax = $tax->parent ? get_term($tax->parent, $tax->taxonomy) : false; 
    } 
} 
add_action('template_redirect', 'load_tax_parent_template'); 
관련 문제