Template di articoli in base alla categoria

In questa guida vi spiegherò come creare template per gli articoli in base alla categoria di provenienza. Questo serve per esempio quando si devono avere 2 template diversi per 2 categorie “Foto” e “Video”, dove nella prima bisogna configurarla per far vedere le foto di una galleria, e la seconda configurarla per far vedere i video del canale Youtube.

Tutto quello che devi fare è inserire nel file functions.php questo codice:

[code language=”php”] add_filter(‘single_template’, ‘check_for_category_single_template’);
function check_for_category_single_template( $t )
{
foreach( (array) get_the_category() as $cat )
{
if ( file_exists(TEMPLATEPATH . "/single-category-{$cat->slug}.php") ) return TEMPLATEPATH . "/single-category-{$cat->slug}.php";
if($cat->parent)
{
$cat = get_the_category_by_ID( $cat->parent );
if ( file_exists(TEMPLATEPATH . "/single-category-{$cat->slug}.php") ) return TEMPLATEPATH . "/single-category-{$cat->slug}.php";
}
}
return $t;
}
[/code]

Quindi se l’abbreviazione (slug) della categoria è “foto”, userai single-category-foto.php, e se l’abbreviazione è “video”, userai single-category-video.php

riferimento