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

Question

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.

<?PHP
$categories = get_categories( array( '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?