2010-06-25 16 views
13

Quiero cambiar el comportamiento de la jerarquía de plantillas predeterminada y forzar a todas las páginas de subcategorías que no tienen su propio archivo de plantilla de categorías a referirse a su archivo de plantilla de categoría principal. En mi otra publicación, Richard M. gave an excellent answer que resolvió el problema para una subcategoría individual. ¿Alguien sabe cómo abstraerlo?Make * ALL * Wordpress Categories usa su plantilla de categoría principal

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

Gracias de antemano.

Respuesta

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

Esto crea un bucle en la jerarquía principal hasta que se encuentra una plantilla inmediata.

+0

Acabo de probar esto y no pude hacerlo funcionar. ¿Te importaría revisarlo dos veces? – Matrym

+2

'TEMPLATEPATH' en lugar de' TEMPLATE_PATH' –

+0

Buen lugar - actualizado :) – TheDeadMedic

2

La variable TEMPLATEPATH podría no funcionar para temas secundarios: se ve en la carpeta del tema principal. Use STYLESHEETPATH ​​en su lugar. p.ej.

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

me preguntaba cómo hacer lo mismo para las taxonomías jerárquicas. La respuesta de TheDeadMedic parece funcionar en ese caso también con algunos ajustes:

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