Search code examples
phpwordpresscustom-post-typewp-list-categories

Get only child terms of custom post type


I have category "trekking" with others chld categories. I need get only trekking child categories but i can't do it. This is my code (works fine, only I must exclude all the others categories but that is not a good/dynamic solution). Thanks!

<ul class="fordesktop">
<?php $customPostTaxonomies = get_object_taxonomies('portfolio');
$category = get_category_by_slug( 'trekking' );
if(count($customPostTaxonomies) > 0)
{
     foreach($customPostTaxonomies as $tax)
     {
         $args = array(
              'orderby' => 'name',
              'show_count' => 0,
              'pad_counts' => 0,
              'hierarchical' => 0,
              'taxonomy' => $tax,
              'title_li' => '',
              'child_of' => $category,
             'exclude' => '10, 19, 20, 21, 22, 26, 29, 30, 31, 35, 36, 37, 41, 42, 43, 44',
             'hide_title_if_empty' => 0
            );

         wp_list_categories( $args );
     }
} ?></ul>

Another way is the next code, but I can't hide empty terms:

<?php
$term_id = 10;
$taxonomy_name = 'portfolio_category';
$termchildren = get_term_children( $term_id, $taxonomy_name );
 
echo '<ul>';
foreach ( $termchildren as $child ) {
    $term = get_term_by( 'id', $child, $taxonomy_name );
    echo '<li><a href="' . get_term_link( $child, $taxonomy_name ) . '">' . $term->name . '</a></li>';
}
echo '</ul>';
?> 

Solution

  • Try using get_term_children():

    // This will give you an array with the ID's of all child categories of 'trekking':
    $cat = get_category_by_slug('trekking');
    $cat_id = $cat->term_id;
    $child_cat_ids = get_term_children($cat_id, 'category');
    

    An alternative approach, if you prefer a list of category objects, instead of IDs would be:

    $cat = get_category_by_slug('trekking');
    $cat_id = $cat->term_id;
    $child_cats = get_categories(['parent' => $cat_id]);
    

    See more info here: https://developer.wordpress.org/reference/functions/get_term_children/ https://developer.wordpress.org/reference/functions/get_categories/

    EDIT:

    if you want to use wp_list_categories() in your code, try this:

    $cat = get_category_by_slug('trekking');
    $cat_id = $cat->term_id;
    $args = array(
            'child_of'   => $cat_id,
    );
    wp_list_categories($args);
    

    EDIT 2:

    Adjusted the solution for custom taxonomies:

    $tax = get_term_by('slug', 'trekking', 'portfolio');
    $tax_id = $tax->term_id;
    $args = array(
    'child_of'   => $tax_id,
    'taxonomy' => 'portfolio',
    'orderby' => 'name',
    'show_count' => 0,
    'pad_counts' => 0,
    'hierarchical' => 0,     
    'title_li' => '',
    'hide_title_if_empty' => 0
    );
    wp_list_categories($args);