Wordpress: Selecting only one post type for WP_list_categories
Similar to this.
I've created two custom post types, and now they are happily sharing two taxonomies, but unfortunately wp_list_categories doesn't allow me to list a taxonomy by only one post type. The code of wp_list_categories relies on get_categories, resulting in an array of categories. So I produced a wp_query thus:
$query = new WP_Query( 'taxonomy=开发者_如何学运维123&term=9&post_type=type' )
so I could do something like:
if (!$query) {
unset $categories[categories]
}
but I keep getting a $query even if there are no such posts.
I did this by cloning the wp_list_categories function, giving it a different name and putting in this code after the line: $categories=get_categories($r):
foreach ($categories as $key => $category){ $temp = array ( 'post_type'=>$r['type'], 'tax_query' => array( array ( 'taxonomy' => $category->taxonomy, 'field' => 'slug', 'terms' => $category->slug )
)
);
$pauli = new wp_query($temp);
if($pauli->post_count==0){
unset($categories[$key]);
}
}
As you can see, it removes categories that do not have any of the post type you need, and then continues the process as wp_list_categories does normally. You may have to add a filter to ensure the category page/taxonomy page called only displays the post type you want, but this depends on what type of permalink you have.
精彩评论