在 WordPress 中,我创建了 2 个自定义帖子类型 Services
& Work
它可以使用 wp 默认类别和标签分类法。
在任何给定的单个帖子页面上,我需要列出该帖子类型可用的类别。
我尝试过使用
$args = array( 'hide_empty' => 1, 'taxonomy' => 'category' ); wp_list_categories( $args );
仅列出与帖子关联的类别,但该列表不考虑帖子类型。
如何仅列出该帖子类型使用的类别?
最佳答案
问题已回答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');
orwp_list_categories_for_post_type('videos', 'order=DESC&title_li=Cats');
and the like.
关于php - WP 仅显示包含该帖子类型的帖子的类别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40369853/