Exclude Children from get_terms

Get_terms does not natively support exclude children. Here is a function that you can use to help keep your front end organized, and structured.

function is_child($term,$taxonomy) {
    $check = get_ancestors($term->term_id,$taxonomy);
    if (!empty($check)) { return true;} else { return false;}
}

I found this particularly useful when trying to Sort Posts By Category, and my categories were nested.

Default:

$taxonomy = get_terms('my_custom_taxonomy');
foreach ($taxonomy as $term) {
    if (!is_child($term,$taxonomy)) {
        // Exclude children from this
    }
};

Sort Posts by Category:

//get all categories then display all posts in each term
$taxonomy = 'category';

// $param_type = 'category__in'; no longer in use
$term_args = array(
  'orderby' => 'name',
  'order' => 'ASC'
);

$terms = get_terms($taxonomy,$term_args);

if ($terms) {

	foreach( $terms as $term ) {
		if (!is_child($term,$taxonomy)) { // trigger exclude children
		    $args = array(
		
		      'tax_query' => array(array( 
			     'taxonomy' => 'category',
			     'field' => 'term_id',
			     'terms' => array($term->term_id), // get the post type term id
		      )), 
		      'post_type' => 'post',
		      'posts_per_page' => -1
		      // 'caller_get_posts'=> 1 DEPRECATED
		      );
		
		    $my_query = null;
		
		    $my_query = new WP_Query($args);
		
		    if( $my_query->have_posts() ) { ?>
		
			    <ul class="category_posts">
			
				    <li><a href="<?php the_permalink(); ?>/category/<?php echo $term->slug; ?>">
					    	<?php echo $term->name;?>
					    </a>
			
					    <ul class="children">
				
					    <?php while ($my_query->have_posts()) : $my_query->the_post(); ?>
				
				        <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
				
				       <?php endwhile; ?>
				
				      </ul>
				  
				  </li>
				  
			    </ul>
		
		 <?php } // end my_query
		
		} // end if exclude children 
		
	} // endforeach

} // end if terms

wp_reset_query();  // Restore global post data stomped by the_post(). ?>

Sourced here.

Leave a Reply

katherine as a flat graphic icon

About Me

I’m an African / Ojibwe First Nations Web Developer living in Winnipeg, Manitoba.

Visit the Tips and Blog to see what I’m working on.