简体   繁体   中英

WP only display categories that contain posts from that post type

In wordpress I've created 2 custom post types Services & Work which can use the wp default category and tag taxonomies.

On any given single post page I need to list the categories available for that post type.

I've tried using $args = array( 'hide_empty' => 1, 'taxonomy' => 'category' ); wp_list_categories( $args ); $args = array( 'hide_empty' => 1, 'taxonomy' => 'category' ); wp_list_categories( $args ); to list only those categories with posts associated but the list doesnt take the post types into account.

How would I only list the categories being used by that post type?

Question answered here :

Put the following in your functions.php :

 function wp_list_categories_for_post_type($post_type, $args = '') { $exclude = array(); // Check ALL categories for posts of given post type foreach (get_categories() as $category) { $posts = get_posts(array('post_type' => $post_type, 'category' => $category->cat_ID)); // If no posts found, ... if (empty($posts)) // ...add category to exclude list $exclude[] = $category->cat_ID; } // Set up args if (! empty($exclude)) { $args .= ('' === $args) ? '' : '&'; $args .= 'exclude='.implode(',', $exclude); } // List categories wp_list_categories($args); } 

Now you can call wp_list_categories_for_post_type('photos'); or wp_list_categories_for_post_type('videos', 'order=DESC&title_li=Cats'); and the like.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM