Skip to content

Instantly share code, notes, and snippets.

@morgyface
Created March 18, 2023 11:45
Show Gist options
  • Save morgyface/edf3808919146826f420e74ad82a92f5 to your computer and use it in GitHub Desktop.
Save morgyface/edf3808919146826f420e74ad82a92f5 to your computer and use it in GitHub Desktop.
WordPress | Get Child Terms
<?php
function get_child_terms ( $term, $tax ) {
$child_terms = array();
if( $term && $tax ) {
$the_term = get_term_by( 'slug', $term, $tax ); // Get term object using the slug
$terms = get_the_terms(get_the_ID(), $tax); // Get the terms attached to the post
if( $the_term && $terms ) {
foreach ( $terms as $term ) {
if( $the_term->term_id == $term->parent ) {
$child_terms[] = $term->name; // Only get the terms where the parent is the current term
}
}
}
}
return $child_terms;
}
?>
@morgyface
Copy link
Author

morgyface commented Mar 18, 2023

Child Terms

Pass in the slug of the parent term and the slug of the taxonomy it belongs to and you will be rewarded with an array of child terms that belong to the parent term and have been assigned to that post.

Will return an empty array if none exist, so typical use would look like:

$child_terms = get_child_terms( 'extreme', 'sports' );
if( !empty( $child_terms ) ) {
    $child_terms_list = implode(', ', $child_terms);
}

Output example:

Skateboarding, Snowboarding, Rock Climbing

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment