+64-3-3595735

Home » Website Development And Support » Coding » Getting Child and Parent Categories For Custom Post Type (CPT) in WordPress

Getting Child and Parent Categories For Custom Post Type (CPT) in WordPress

Jump to: Get CPT Parents   ||   Get CPT Children

Summary

I use CPTs a lot for WordPress as it can capture field data for a client making it easier to get pages easily laid out with information.

One issue with this is working with Taxonomies / Categories becomes difficult as WordPress functions ( like get_categories) dont work with CPTs.
I wrote the two following pieces of code to allow me to:

  1. Create breadcrumbs showing the category hierarchy of the CPTs
  2. Display sub categories of the current category as buttons  / links

This code is used inside of custom taxonomy pages but should work when called from other page and post types. In this example I use get_queried_object to discover the taxonomy and ID of the page / post I am currently viewing.  $post->id should work just as well and you can also hard code the taxonomy name into your calls.

$term = get_queried_object(); // Getting the term / taxonomy information for the current post

Get The Parents / Grandparent And Ancestor Categories

To Get parents, grandparents etc of the current post.

$term = get_queried_object(); // Getting the term / taxonomy information for the current post
$parent_array = get_category_parent_array($term->term_id, $term->taxonomy);
// Calling it manually or with another way of getting the id will work too
// $parent_array = get_category_parent_array($post->id, 'my_custom_taxonomy');  

// The following prints out the array but you are free to parse the structure as you want for breadcumbs
highlight_string("<?php\n\$data =\n" . var_export($parent_array , true) . ";\n?>");

// And the function to get the parents / grand parents

/**
 * @param $category_id          The CPT / Category Id we want to get parents for
 * @param $category_taxonomy    The taxonomy name of the CPT categories you want to get
 *
 * @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;
        }

    }

}

If we use a Taxonomy / Category hierarchy that looks like Cars->Ford->Falcon  the above call returns an array similar to


<?php
$data =
array (
0 =>
array (
'id' => 260,
'slug' => 'cars-makes',
'name' => 'Cars',
'url' => 'https://example.com/automobile_category/car-makes/',
),
1 =>
array (
'id' => 261,
'slug' => 'ford',
'name' => 'Ford',
'url' => 'https://example.com/automobile_category/ford/',
),
);
?>

 

Get The Children And Display Them

Getting the children of the current category is much simpler. The example below only returns direct children of the current category, not grand children. However using a similar process to the above function could get you a hierarchy or tree of descendants.

$term = get_queried_object(); // Getting the term / taxonomy information for the current post

<?php 
$children = get_terms(['taxonomy'=$term->taxonomy,'parent'=>$term->term_id]);
if ( !empty( $children ) ){
                foreach ( $children as $child ) { ?>
                    <a href="<?php echo get_category_link( $child->term_id ) ?> "class="category__link"><?php echo $child->name; ?></a>
                    <?php
                }
}?>

Enjoy.