Created
March 18, 2023 11:45
-
-
Save morgyface/edf3808919146826f420e74ad82a92f5 to your computer and use it in GitHub Desktop.
WordPress | Get Child Terms
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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; | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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:
Output example: