skip to Main Content

I am trying to get list of only child categories of custom taxonomy, but getting output as all parent and child terms.

$countries = get_categories(array(
    'hide_empty'      => true,
    'taxonomy' => 'locations-category',
    'orderby' => 'name',
    'order'   => 'ASC',
    'tax_query' => array(
        array(
            'taxonomy'         => 'locations-category',
            'terms'            => 0,
            'field'            => 'parent',
            'compare'         => '!='
        )
    )
));
echo "<pre>";
print_r($countries);
echo "</pre>";`

Tried this as well but getting error as undefined variable:

$categories = get_terms('locations-category', 'parent!=0');
echo "<pre>";
print_r($countries);
echo "</pre>";

Basically I want to get categories where 'parent' != 0

2

Answers


  1. Probably best to use PHP to filter the results from get_category() (untested):

    $terms = get_category( array(
        ...
    ) );
    
    $child_terms = array_filter( $terms, static function ( $term ) {
        return 0 !== $term->parent;
    } );
    
    Login or Signup to reply.
  2. $taxonomy = 'your_custom_taxonomy'; // Replace with your actual custom taxonomy name
    
    $terms = get_terms(array(
        'taxonomy' => $taxonomy,
        'hide_empty' => false, // Set to true if you want to exclude empty terms
    ));
    $child_categories = array();
    foreach ($terms as $term) {
        $child_ids = get_term_children($term->term_id, $taxonomy);
        
        foreach ($child_ids as $child_id) {
            $child_category = get_term_by('id', $child_id, $taxonomy);
            $child_categories[] = $child_category;
        }
    }
    print_r($child_categories);
    Please make sure to replace 'your_custom_taxonomy' with the actual name of your custom taxonomy in the code.
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search