Exclude Child Terms From Parent Posts

How can I exclude the child term posts from showing up in the parent term posts output?? Right now it’s duplicating in both parent and child term outputs.

 //Function to display posts grouped by taxonomies
    function display_posts_per_taxonomies($parent_term, $post_type="beat_posts", $taxonomy = 'beats'){
    $parent_posts = get_posts(array(
    'tax_query' => array( array(
    'taxonomy' => $taxonomy,
    'field' => 'slug',
    'terms' => $parent_term
        )),
        'post_type' => $post_type
    ));
    echo '<ul>';
    foreach($parent_posts as $post){
        echo "<li>{$post->post_title}</li>"; 
    }
    $children_terms = get_terms($taxonomy, array(
        'parent' => get_term_by('slug', $parent_term, $taxonomy)->term_id
    )); 
    foreach($children_terms as $term){
        echo '<li>';
        display_posts_per_taxonomies($term->slug, $post_type, $taxonomy);
        echo '</li>';
    }
    echo '</ul>';   
}

Below is what I’m trying to get rid of.

<ul>
<li>adsf</li>
<li>ergerg</li> <---get rid of this one (duplicate)
<li>asdfasdfsdf</li> <---get rid of this one (duplicate)
<li>rthhdhdfhdhdfhdfg</li>
<li>
<ul>
<li>ergerg</li>
<li>asdfasdfsdf</li>
</ul>
</li>
</ul>

3 Answers
3

In your get_terms() call, try setting the hierarchical option to false:

$children_terms = get_terms($taxonomy, array(
        'parent' => get_term_by('slug', $parent_term, $taxonomy)->term_id,
        'hierarchical' => false
));

This option normally defaults to true, which is probably why you’re getting the extra copies.

Leave a Comment