0
votes

I have a custom post type set up, with a number of categories and sub categories.

What I am trying to do is create a page that shows all the posts in a specific category, with a menu that lists all the category sub categories so the posts can then be filtered.

I have tried copying the archive template and renaming it taxonomy-(my-custom-taxonomy).php which then if I go to the slug shows certain posts, and using <?php wp_list_categories(); ?> but I just want a list of all the sub-categories of a specific category, and to filter those posts. I am struggling to show these and use one template for all categories and children.

1
You use category-slug.php instead of taxonomy for category filtering. To only show children, <ul> <?php wp_list_categories('orderby=id&show_count=1&use_desc_for_title=0&child_of=8'); ?> </ul> Where 8 is the category ID.Aibrean
I want to use one template for all pages so this answer would not work. Where has the other answer gone? I thought it was almost there.Hue
They must have deleted their answer.Aibrean

1 Answers

0
votes

You can use

$term_id = get_queried_object()->term_id;

and

$tax= get_query_var( 'taxonomy' ) 

to return the details of the current term and taxonomy being viewed in your taxonomy.php page.

You can then use that info with get_term_children to get the child terms of the current term being displayed. For examples, see the link provided

EDIT

Your code should look like this

<?php
$term_id = get_queried_object()->term_id;
$taxonomy_name = get_query_var( 'taxonomy' ); 
$termchildren = get_term_children( $term_id, $taxonomy_name );

foreach ( $termchildren as $child ) {
    echo '<ul>';
        $term = get_term_by( 'id', $child, $taxonomy_name );
        echo '<li><a href="' . get_term_link( $child, $taxonomy_name ) . '">' . $term->name . '</a></li>';

    $args = array(
        'tax_query' => array(
            array(
                'taxonomy' => $taxonomy_name,
                'field'    => 'slug',
                'terms'    => $term->slug,
            ),
        ),
    );
    $the_query = new WP_Query( $args );

    while ( $the_query->have_posts() ) {
        $the_query->the_post();
        echo '<p>' . get_the_title() . '</p>';
    }
    wp_reset_postdata();

    echo '</ul>';   

}
?>