wordpress如何获取自定义文章类型文章的分类(附代码示例)

作者: 站长 上传时间: 浏览: N/A 下载: N/A 格式: N/A 评分: N/A

1、以下代码加入function.php

function wp_list_categories_for_post_type($post_type, $args = '') {
$exclude = array();

// 获取指定文章类型(或自定义文章类型)文章的分类
foreach (get_categories() as $category) {
$posts = get_posts(array('post_type' => $post_type, 'category' => $category->cat_ID));

//如果没有查到
if (empty($posts))
// 添加分类id到排除列表
$exclude[] = $category->cat_ID;
}

// 设置查询参数arg
if (! empty($exclude)) {
$args .= ('' === $args) ? '' : '&';
$args .= 'exclude='.implode(',', $exclude);
}

//显示分类
wp_list_categories($args);
}

2、使用方法
例如:有一个自定文章类型为电影movie,获取电影的分类
wp_list_categories_for_post_type('movie');

其他查询参数也适用于上述方法:
wp_list_categories_for_post_type('movie','order=DESC&title_li=Cats');

Leave a Comment