Studying the above functions and trying to get them to work, when I was in a sub category, most of the time it returned 0. I believe this is because of the else statement, which is stopping the for loop from looping.
Anyway, I wrote my own function… it returns the parent category ID for any category down to one level.
function get_parent_category() {
global $cat;
foreach ((get_the_category()) as $cato) {
if($cat==$cato->cat_ID) {
if($cato->category_parent==0)
return $cat;
else
return $cato->category_parent;
}
}
return $cat;
}