Создайте функцию в functions.php
function smart_category_top_parent_id ($catid) {
while ($catid) {
$cat = get_category($catid); // get the object for the catid
$catid = $cat->category_parent; // assign parent ID (if exists) to $catid
// the while loop will continue whilst there is a $catid
// when there is no longer a parent $catid will be NULL so we can assign our $catParent
$catParent = $cat->cat_ID;
}
return $catParent;
}
Затем вызывайте эту функцию в нужном вам месте:
$category = get_the_category($post->ID); //post id
$catid = $category[0]->cat_ID;
$top_level_cat = smart_category_top_parent_id ($catid);