I found most of the above did not work for Custom Post Types. So I wrote the following function.
Given the ID of the current ( child ) category, it works its way up the chain to give the parent(s) of the category.
It returns an array containing url, name, slug and id of parents.
/**
* @param $category_id
*
* @return array Returns either empty array if no parents or
* an array of categories from base category[0] to parent category
* The array has a sub array of ['id'] ['name'] ['slug'] ['url']
*
*/
function get_category_parent_array( $category_id, $category_taxonomy = 'category'){
$category_id = abs((int)$category_id);
$category_taxonomy = sanitize_key( $category_taxonomy);
// Sanity check for top parent - ( id = 0 )
if( 0 == $category_id ){
return array();
}
$child_category = get_term( $category_id, $category_taxonomy);
if( empty($child_category)){
return array();
}
$parent_category_id = $child_category->parent;
if( 0 == $parent_category_id ){
return array(); // We cant get category 0.
}
// We have checked if the parent_id is 0 but double check here for other issues causing empty parent category
$parent_category = get_term( $parent_category_id, $category_taxonomy);
if ( empty ( $parent_category ) ){
return array();
}
// Prepare the return array
$parent_array = array();
$parent_array['id'] = $parent_category_id;
$parent_array['slug'] = esc_attr($parent_category->slug);
$parent_array['name'] = esc_attr($parent_category->name);
$parent_array['url'] = esc_url(get_term_link( $parent_category));
if ( 0 == $parent_category_id ){
return $parent_array;
}else{
$new_parent = get_category_parent_array($parent_category_id, $category_taxonomy );
if(! empty( $new_parent ) ){
return array( $new_parent, $parent_array);
}else{
return $parent_array;
}
}
}
For example. In a tree of Home>Products>Platic-Bags>Poly-Bags>3muBags
Where the child / current category is 3mu it returned the following:
array (
0 =>
array (
'id' => 260,
'slug' => 'plastic-bags',
'name' => 'Plastic Bags',
'url' => 'https://example.com/product_category/plastic-bags/',
),
1 =>
array (
'id' => 261,
'slug' => 'polybags',
'name' => 'Polybags',
'url' => 'https://exmapl.com/product_category/polybags/',
),
);