For the new geeks.co.uk design I needed a way of finding which top level category any given post was in and use that in the CSS to make various design elements of the page the specific colour of that top level category.
On geeks.co.uk, some posts are in a top level category, eg all News articles, and some are in sub categories, eg some Game Reviews are in Wii but not PSP etc.
Also, CSS won’t work with spaces in the names of labels so for categories like “Game Reviews” we have to remove the space to be useful as a CSS label.
Sometimes you want the function call to echo the category name to the page, eg when it’s used as a title of the page or in breadcrumbs. Sometimes you just want it returned to use in a CSS label, for example.
So here is my function:
function get_top_cat($css = false, $echo = false){
$maffcat = (array) get_the_category();
$maffpar = get_cat_name($maffcat[0]->category_parent);
if ($maffpar == ''){
$maffcat = (array) get_the_category();
$maffpar = $maffcat[0]->cat_name;
}
if ($css){$maffpar = str_replace (" ", "", $maffpar);}
if ($echo){ echo $maffpar;}
else{
return $maffpar;
}
}
Stick that in your theme’s functions.php and you should be able to call it by, for example,
get_top_cat('', 'true') - will put top category name with spaces on your page
get_top_cat('true', '') - will put top category name without spaces in your code
in your webpage files like single.php, archive.php etc
Nb. this works for two-level categories – it seems that this could easily be extended for more levels by further nesting.
Recent Comments