Skip to content

Instantly share code, notes, and snippets.

@flegfleg
Created August 8, 2020 21:50
Show Gist options
  • Save flegfleg/78dcfe983f65db59c1456b5425d823e7 to your computer and use it in GitHub Desktop.
Save flegfleg/78dcfe983f65db59c1456b5425d823e7 to your computer and use it in GitHub Desktop.
/**
* Get the top level parent category, even on sub-categories
* @return string
*/
function _s_get_parent_cat() {
$term = get_queried_object();
$children = get_terms( $term->taxonomy, array(
'parent' => $term->term_id,
'hide_empty' => false
) );
$ancestor_ids = get_ancestors( $term->term_id, $term->taxonomy );
if ( $children ) { // cat has children
return $term->term_id;
} else { // cat has no children
$parent_id = $ancestor_ids[0];
return $parent_id;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment