Last active
March 20, 2021 10:50
-
-
Save pixeldevsio/11b3f80e322eb0f10fdf1d6c9ce97d32 to your computer and use it in GitHub Desktop.
WordPress helper functions to display child terms by parent slug
This file contains 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 | |
// 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