Get a list of Terms for a specific category

I have a category called News and a custom Taxonomy called Filters which is a hierarchical Taxonomy.

When a user creates a Post, they select a subcategory under news and a sub-filter under the Filter Taxonomy.

Now I am trying to list all the ‘Sub-Categories’ and ‘Filters’ when a user navigates to /news.

Listing the Sub-Categories for the ‘News’ category was easy. But I can’t seem to figure out a way to list all the ‘Sub-Filters’ for the Taxonomy ‘Filters’ limited to only the category ‘News’.

Here is the code I used for getting a list of sub-categories for the category news:

function get_child_categories()
{
    if (is_category()) {
        $thiscat = get_category(get_query_var('cat'));
        $catid = $thiscat->cat_ID;
        $args = array('parent' => $catid);
        $categories = get_categories($args);

        return $categories;
    }

    return false;
}

I was hoping for a similar function which will list all terms for taxonomy ‘Filters’ but only limited to the category ‘News’. Here is a screenshot of what I am trying to achieve:

In the screenshot below ‘/news’ is related to the ‘News’ category in the admin area. So if a user goes to /news, the front end should list all the posts for the ‘News’ Category.

The page should also list all the sub-categories under the Category ‘News’. This is done as you can see from the horizontal list of Sub Categories.

Now the user can also select a Filter as can be seen in the admin UI. What I am trying to achieve is to list all the Filters for any post that may be categorized under ‘News’ and display in the horizontal list where under ‘Filters’. This will then be used to filter the posts when the user clicks for example ‘World News’ to list only the posts that have the Filter ‘World News’ checked.

enter image description here

Current Category/Taxonomy in the Admin Area when editing the post

enter image description here

2 Answers
2

The following code will do it. Please change the ‘filter’ text in the below code to whatever filters taxonomy name you have set.

if(is_category() ){

    $thiscat = get_queried_object_id(); 
    $filter_tax = array();
    $args = array( 'category' => $thiscat );
    $lastposts = get_posts( $args );

    foreach ( $lastposts as $post ){
        setup_postdata( $post );
        $terms = get_the_terms( $post->ID, 'filter' ); // Change the taxonomy name here

        if ( $terms && ! is_wp_error( $terms ) ){

         foreach ( $terms as $term ) {
            $filter_tax[] = $term;
         }

        }
    }
    wp_reset_postdata();

    if( !empty($filter_tax) ){
        print_r($filter_tax);
    } else {
        echo 'No filter set.';
    }

}

Leave a Comment