Get Current WordPress top level category on posts and taxonomy templates
Whether on a category template, a sub category template, or a post need to be able to get the top level category ID.
For instance, say a top level category was Dogs with an ID of 2. If on the Dogs category template it would show 2. If on sub category such as Labrador it would also show 2. If on a post in Labrador it would show 2. And of course if a on a category or sub category or post of another top level category it would show that id instead.
A post on Stack Overflow says to get that use:
$topcat = get_the_category(); echo $topcat->category_parent;
When using that it shows the current category (not the top level). So if on Dogs it shows 2, but if on Labrador it shows the Labrador category ID, etc.
Tried a few other Stack Overflow answers but each with their own issues. Can this be accomplished easily with get_ancestors or another simple method?