2010-06-25 28 views
13

Tôi muốn thay đổi hành vi phân cấp mẫu mặc định và buộc tất cả các trang cấp danh mục phụ không có tệp mẫu danh mục riêng để tham chiếu tệp mẫu danh mục gốc của chúng. Trong bài đăng khác của tôi, Richard M. gave an excellent answer đã giải quyết được vấn đề cho một danh mục phụ riêng lẻ. Có ai biết làm thế nào để trừu tượng nó?Tạo * ALL * Danh mục Wordpress sử dụng Mẫu danh mục gốc

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'); 

Xin cảm ơn trước.

Trả lời

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'); 

Điều này lặp lên cấp bậc cha mẹ cho đến khi tìm thấy mẫu ngay lập tức.

+0

Tôi vừa thử điều này và không thể làm việc đó. Bạn có phiền khi kiểm tra nó không? – Matrym

+2

'TEMPLATEPATH' thay vì' TEMPLATE_PATH' –

+0

Điểm tốt - được cập nhật :) – TheDeadMedic

2

Biến TEMPLATEPATH có thể không hoạt động đối với chủ đề con - trông trong thư mục chủ đề mẹ. Thay vào đó hãy sử dụng STYLESHEETPATH. ví dụ.

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

tôi đã tự hỏi làm thế nào để làm điều tương tự cho phân loại theo nguyên tắc. Câu trả lời của TheDeadMedic dường như hoạt động trong trường hợp đó quá w/một vài điều chỉnh:

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'); 
Các vấn đề liên quan