The following snippet saved me a bunch time when dealing with a recent project. The scenario was I created 2 custom post types and they share the default “category” taxonomy with Posts. On the post type archive page, I have to display the category links so users can filter the posts.
The difficult part was I wanted to only show categories that have posts in the current post type. The following snippet came from StackExchange, with the function hook to the
terms_clauses filter, now we can use a custom argument called
post_types in the function
post_types can be an array so you can get terms like this:
get_terms( array( 'post_types' => array('post', 'cpt1', 'cpt2'), 'taxonomy' => 'category' ) );
get_terms( array( 'post_types' => 'cpt1', 'taxonomy' => 'category' ) );
Please go to StackExchange to upvote the answer if you find it helpful to you too.
I’m a senior web developer helping clients build their websites to grow businesses. Currently I’m based in Taipei, Taiwan.
I write things about WordPress, AngularJS and life. Whenever you’d like to find someone to talk about these topics, just get in touch!