在 WordPress 中,如果你想获取指定文章类型(post type)关联的分类法(taxonomies),可以使用 get_object_taxonomies() 函数。这个函数会返回与指定文章类型关联的所有分类法。
示例代码
$post_type = 'your_post_type'; // 替换为你的文章类型
$taxonomies = get_object_taxonomies( $post_type );//分类法的名称或对象的数组
if ( ! empty( $taxonomies ) ) {
echo '与文章类型 "' . $post_type . '" 关联的分类法有:';
echo '<ul>';
foreach ( $taxonomies as $taxonomy ) {
echo '<li>' . $taxonomy . '</li>';
}
echo '</ul>';
} else {
echo '没有找到与文章类型 "' . $post_type . '" 关联的分类法。';
}
参数说明
$post_type:你想要获取分类法的文章类型名称。$output(可选):指定返回结果的格式,可以是names(默认,返回分类法名称数组)或objects(返回分类法对象数组)。$operator(可选):指定操作符,可以是and或or,默认是and。
示例输出
假设你有一个自定义文章类型 book,并且它关联了 genre 和 author 两个分类法,那么上述代码的输出可能是:
与文章类型 "book" 关联的分类法有:
- genre
- author
获取分类法对象
如果你想获取分类法的对象(包含更多详细信息),可以将 $output 参数设置为 objects:
$taxonomies = get_object_taxonomies( $post_type, 'objects' );
这样,$taxonomies 将是一个包含分类法对象的数组,你可以访问每个分类法的属性,如 name、label、hierarchical 等。
示例代码(获取分类法对象)
$post_type = 'your_post_type'; // 替换为你的文章类型
$taxonomies = get_object_taxonomies( $post_type, 'objects' );
if ( ! empty( $taxonomies ) ) {
echo '与文章类型 "' . $post_type . '" 关联的分类法有:';
echo '<ul>';
foreach ( $taxonomies as $taxonomy ) {
echo '<li>' . $taxonomy->label . ' (' . $taxonomy->name . ')</li>';
}
echo '</ul>';
} else {
echo '没有找到与文章类型 "' . $post_type . '" 关联的分类法。';
}
总结
通过 get_object_taxonomies() 函数,你可以轻松获取与指定文章类型关联的分类法,并根据需要处理这些分类法的名称或对象。

