Show only the grandchildren (using get_terms)

I’m working with a hierarchical taxonomy (named “world”) that has 3 levels to it (Regions > Countries > Indigenous Peoples). At the moment I’m using a modified version of this code to paginate all the results on a single page.

Here’s the important part

Read More
$page = ( get_query_var('paged') ) ? get_query_var( 'paged' ) : 1;
// number of tags to show per-page
$per_page = 24;
$offset = ( $page-1 ) * $per_page;
$args = array( 'number' => $per_page, 'offset' => $offset, 'hide_empty' => 1,'hierarchical ' => true
);

and

$taxonomy = 'world';
$tax_terms = get_terms( $taxonomy, $args );

As expected, this returns a paginated list of all the terms associated with my taxonomy. The problem is, I only actually need to show the grandchildren, in this case, "Indigenous Peoples".

I’m tempted do it manually, but I’d rather not serve up a list of 450+ terms to include (or 80 terms to exclude) unless it’s absolutely necessary.

Your help would be most appreciated.

Related posts

Leave a Reply

2 comments

  1. I think for each term you should check that it has a parent but not have any childern

    So you code may look like

        $taxonomy = 'world';
        $tax_terms = get_terms( $taxonomy );
        foreach ($tax_terms as $value){
            $args=array(
                'child_of'=> $value->term_id,
                );
            //get all child of current term
            $child = get_terms( $taxonomy, $args );
            if( $value->parent != '0' && count($child) =='0'){
                echo $value->slug;
                echo '<br/>';
                //do something because it's your lowest level term which have parent but not have any childern
            }
        }
    
  2. Why don’t you use “parent” parameter of get_terms

    $page = ( get_query_var('paged') ) ? get_query_var( 'paged' ) : 1;
    // number of tags to show per-page
    $per_page = 24;
    $offset = ( $page-1 ) * $per_page;
    $args = array( 'number' => $per_page, 'offset' => $offset, 'hide_empty' => 1,'hierarchical ' => true,
      'parent'=>'term_id of Indigenous Peoples or whatever parent's child you want.'
    );
    
    $taxonomy = 'world';
    $tax_terms = get_terms( $taxonomy, $args );