Currently I use the following code to output all categories within this custom taxonomy in a custom post type:

  $args = array(
        'post_type'      =>  'video_cpt',
        'post_status'    =>  'publish',
        'posts_per_page' =>  -1,
        'orderby'        => 'publish_date',
        'order'          => 'DESC',

  $video_query  = new WP_Query( $args );

  $videos_post_objects = $query;

  while ($video_query->have_posts()) {
    $terms = get_the_terms( $post->ID, 'video_categories' );
    $term = array_shift( $terms );

Is it possible to use get_the_terms (preferably by name instead of taxonomy ID) in the same manner to get the subcategories of a category from a custom taxonomy in a custom post type?


video categories

how would I use get_the_terms (in a similar way as above) to only list out apples, oranges, bananas?

  • There is no such thing as 'orderby' => 'publish_date',, instead you'll need to use 'orderby' => 'date',
    – user2015
    Oct 2, 2018 at 19:26

1 Answer 1


When you use get_the_terms() it returns a term object. One of the fields is 'parent' which stores the ID of the term parent. So you can compare the current term's parent to the parent term that you are looking for.

$desired_parent_name = 'fruits';    
$desired_parent_id = get_term_by('name', $desired_parent_name)->term_id;

foreach ($terms as $term) {
    if $term->parent == $desired_parent_id {
        //do something here
        echo $term->name;

To be honest I don't quite understand this line of your code > $term = array_shift( $terms ); since I don't see what you are doing with this term variable.

There's two ways that you can find all of the terms that have matching posts. One is to find all the posts and check all of their terms, which is what you're doing. The other is to find all of the terms and see if they have any matching posts. Which to use might depend on how many terms and how many posts you have, but I'm inclined to think that looping through the terms is faster.

Here is how to get all of the terms with the parent 'fruit' and then see which have posts in your type.

$allterms = get_terms( array( 'parent' => $desired_parent_id ) );
foreach ($allterms as $term) {
    $args = array(
        'post_type'      =>  'video_cpt',
        'post_status'    =>  'publish',
        'posts_per_page' =>  1,
        'tax_query'      => array ( array (
            'taxonomy' => 'video_categories',
            'terms'    => $term->term_id,
        'fields'         => 'ids'
  ); //the fields parameter is to return just the post ids rather than the whole posts
      $video_query  = new WP_Query( $args );
      if ($video_query->have_posts()) {
         //there's videos that match this term, so do something
         echo $term->name;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.