Search code examples
wordpresstaxonomytaxonomy-terms

How do I display posts from tagchildren of taxonomy tagparent


Firstly, I'm trying to display all tags from a taxonomy called 'group'. However, this taxonomy currently contains two tags, from which one of of them has multiple tagchildren.

Update: I should have mentioned it was for a particular post type.

I'd lik to display all posts belonging to those children. So the final result should look something like this:

  • Parent Tag A
    • Child tag
      • Post data
    • Child tag
      • Post data
    • etc...
  • "Parent" Tag B

    <?php
    $taxonomyName = "group";
    $terms = get_terms($taxonomyName,array('parent' => 0));
    foreach($terms as $term) {
            echo '<a href="'.get_term_link($term->slug,$taxonomyName).'">'.$term->name.'</a>';
            $term_children = get_term_children($term->term_id,$taxonomyName);
            echo '<ul>';
            foreach($term_children as $term_child_id) {
                    $term_child = get_term_by('id',$term_child_id,$taxonomyName);
                    echo '<li><a href="' . get_term_link( $term_child->name, $taxonomyName ) . '">' . $term_child->name . '</a></li>';
            }
            echo '</ul>';
    }
    ?>
    

Solution

  • May be you should try this...

    I hope this will work...

    $taxonomyName = "group";
    $terms = get_terms($taxonomyName,array('parent' => 0));
    echo '<ul>';
    foreach($terms as $term)
    {
        echo '<li><a href="'.get_term_link($term->slug,$taxonomyName).'">'.$term->name.'</a>';
        $term_children = get_term_children($term->term_id,$taxonomyName);
        echo '<ul>';
        foreach($term_children as $term_child_id)
        {
            $term_child = get_term_by('id',$term_child_id,$taxonomyName);
            echo '<li><a href="' . get_term_link( $term_child->name, $taxonomyName ) . '">' . $term_child->name . '</a>';
            echo '<ul>';
            $tax_arg = array(
                'post_type' => 'post',
                'posts_per_page' => -1,
                'post_status' => 'publish',
                'tax_query' => array(
                    array(
                        'taxonomy' => $taxonomyName,
                        'field' => 'id',
                        'terms' => $term_child_id
                    )
                )
            );
            $posts = get_posts($tax_arg);
            foreach($posts as $post)
            {
                echo '<li><a href="' . get_permalink($post->ID) . '">' . $post->post_title . '</a></li>';
            }
            echo '</ul>';
            echo '</li>';
        }
        echo '</ul>';
        echo '</li>';
    }
    echo '</ul>';