よく書く処理なので。
WP_Termオブジェクトを配列で返す場合
function find_ancestor_categories($category_id, $categories = []) {
$category = get_category($category_id);
$categories[] = $category;
if($category->parent) {
$categories = find_ancestor_categories($category->parent, $categories);
}
return $categories;
}
term_idを配列で返す場合
function find_ancestor_category_ids($category_id, $category_ids = []) {
$category = get_category($category_id);
$category_ids[] = $category->term_id;
if($category->parent) {
$category_ids = find_ancestor_category_ids($category->parent, $category_ids);
}
return $category_ids;
}