Only show categories that have posts within custom post type

by egr103   Last Updated December 07, 2017 10:08 AM

My custom post type & built in Wordpress blog posts SHARE the built in categories.

I have a piece of code that loops through and shows all (built in) categories that have posts assigned to them on 'archive-work.php'

I only want to show the categories that have CPT (work) posts assigned to them and NOT show any other posts (i.e. any blog posts that may be in the same category). However, my code below is showing all categories that have any post from any post type, how do I fix this to only show categories from the Work CPT?

<?php
          $args=array(
            'name' => 'category',
            'public'   => true,
            '_builtin' => true

          );
          $output = 'names'; // or objects
          $operator = 'and';
          $taxonomies=get_taxonomies($args,$output,$operator);
          if  ($taxonomies) {
            foreach ($taxonomies  as $taxonomy ) {
              $terms = get_terms([
                'post_type' => array( 'work' ),
                'taxonomy' => $taxonomy,
                'hide_empty' => 1,
              ]);
          foreach ( $terms as $term) {

            if ($term->slug == 'all-articles') {} else {?>
              <button class="filter--item" data-filter=".<?php echo $term->slug; ?>"><?php echo $term->name; ?> <span class="checkbox"><i class="i-check"></i></span></button>
          <?php } } } } ?>


Answers 1


You can use get_object_taxonomies() which will allow you to get taxonomies according to post type. Later you can follow the same procedure above.

Sid
Sid
December 07, 2017 10:01 AM

Related Questions


Help with Multi Level Category Archive Page

Updated August 13, 2016 08:03 AM

Filter WordPress custom post type with taxonomy

Updated March 02, 2016 01:03 AM

Category/Taxonomy Template not loading

Updated July 07, 2015 15:03 PM

Custom Post Type Custom Archive Page Not Working

Updated October 02, 2017 04:08 AM

Categories and Tags not working!

Updated August 20, 2016 09:03 AM