php – Hide categories that are not used in the post type


I have a situation where I need to display categories on the Archive Page of CPTs, but if the category is not used anywhere in the CPT, it needs to be excluded from the list.

For example, I have a CPT for “Books” and “Movies”. I created a post inside the Books CPT and attached it to the “Horror” category. I also created another post in the “Books” CPT and removed all the categories from it.

Now, when I add the below code to the archive page, it will show the “Horror” category in the “Books” Archive page as well as on the “Movies” Archive page.

$categories = get_categories(
      'orderby' => 'name',
      'order'   => 'ASC'
foreach ($categories as $category) {
    echo '<li class="filter-tab-list archive__filterizr-btn" data-filter="' . $category->term_id . '"> ' . $category->name . ' </li>';

Is there any way I can exclude the empty category from the “Movies” archive page?

Thanks in advance 🙂

naveenkharwar 8 months 2022-06-10T13:45:46-05:00 0 Answers 0 views 0

Leave an answer