我在wordpress中创建了2个自定义帖子类型Services
&Work
可以使用wp默认的类别和标签分类法。
在任何给定的单个帖子页面上,我需要列出该帖子类型可用的类别。
我试过使用$args = array( 'hide_empty' => 1, 'taxonomy' => 'category' ); wp_list_categories( $args );
只列出那些与帖子相关的类别,但列表不考虑帖子类型。
我如何只列出该帖子类型使用的类别?
问题解答:
在您的
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); }
现在您可以调用
wp_list_categories_for_post_type('photos');
或wp_list_categories_for_post_type('videos', 'order=DESC&title_li=Cats');
等。