Skip to content

Instantly share code, notes, and snippets.

@pixeldevsio
Last active March 20, 2021 10:50
Show Gist options
  • Save pixeldevsio/11b3f80e322eb0f10fdf1d6c9ce97d32 to your computer and use it in GitHub Desktop.
Save pixeldevsio/11b3f80e322eb0f10fdf1d6c9ce97d32 to your computer and use it in GitHub Desktop.
WordPress helper functions to display child terms by parent slug
<?php
// helper function to get term children
function pd_get_term_children($slug, $term_type = 'category'){
// set up category by slug
$category = get_term_by('slug', "{$slug}", "{$term_type}");
// get out if no category
if(!$category){return;}
$cat_id = $category->term_id;
//get the children as an array
$cat_children = get_term_children( $cat_id, "{$term_type}");
// call a display function to show the children
return pd_display_term_children($cat_children, $term_type);
}
// helper function to display term children
function pd_display_term_children($cat_children, $term_type){
echo '<ul>';
foreach ( $cat_children as $child ) {
$term = get_term_by( 'id', $child, $term_type );
echo '<li><a href="' . get_term_link( $child, $taxonomy_name ) . '">' . $term->name . '</a></li>';
}
echo '</ul>';
}
//use case example
pd_get_term_children('parentcat', 'category');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment