Get WordPress Current Category ID and Top Level Parent Category ID on all category and post templates
In WordPress, trying to get get the current category id and separately how to get the parent category id, regardless of whether you are on a top level category archive template, sub category template, or an individual post?
There are other posts here on similar topics but in some seem inefficient or no longer working, or work on one template file such as category, but not on say an individual post.
Is there a current best practice such as an example using get_ancestors?
As another example, here is something that is almost perfect. It works on sub categories. At first thought it wasnt working on single, but that was because the example post was assigned to multiple categories. So the only issue is when viewing on a top level category, "echo $hierarchy;" shows the correct number but "echo $category->term_id;" does not. "echo $category->term_id;" should show the same number as "echo $hierarchy;" when on a top level category.
<?php $category = get_the_category(); $hierarchy = array_reverse( get_ancestors( $category->term_id, 'category' ) ); $hierarchy = $category->term_id; // Show current category ID echo $category->term_id; //Show Parent category ID echo $hierarchy; ?>