WordPress自定义文章类型为站点内容组织提供了很大灵活性,很多站点会为自定义文章类型绑定专属的分类法,实际开发中经常需要获取这些分类法下的术语数据,用于导航、筛选、列表展示等场景。

使用get_terms函数获取分类术语
get_terms是WordPress内置的用于获取分类术语的核心函数,只要正确配置参数就可以精准获取自定义文章类型关联的分类术语。首先需要在注册自定义分类法的时候,确保该分类法绑定到了目标自定义文章类型上。
注册自定义分类法的示例代码:
<?php
// 注册自定义文章类型
function register_custom_post_type() {
$args = array(
'public' => true,
'label' => '产品'
);
register_post_type( 'product', $args );
}
add_action( 'init', 'register_custom_post_type' );
// 注册自定义分类法,绑定到product文章类型
function register_custom_taxonomy() {
$args = array(
'public' => true,
'label' => '产品分类',
'hierarchical' => true, // 设置为true表示是分类,false表示是标签
'object_type' => array( 'product' ) // 绑定到自定义文章类型
);
register_taxonomy( 'product_cat', array( 'product' ), $args );
}
add_action( 'init', 'register_custom_taxonomy' );
?>
获取该分类法下所有术语的代码:
<?php
// 获取product_cat分类法下的所有术语
$terms = get_terms( array(
'taxonomy' => 'product_cat', // 指定分类法名称
'hide_empty' => false, // 是否隐藏没有关联文章的术语,false表示显示所有
) );
if ( ! empty( $terms ) && ! is_wp_error( $terms ) ) {
foreach ( $terms as $term ) {
echo '<p>分类名称:' . $term->name . ',分类ID:' . $term->term_id . '</p>';
}
}
?>
通过WP_Query获取关联分类术语
如果需要获取某个自定义文章类型下已发布文章关联的所有分类术语,可以通过WP_Query先查询出对应的文章,再提取文章关联的术语。
<?php
// 查询product文章类型的所有已发布文章
$query_args = array(
'post_type' => 'product',
'post_status' => 'publish',
'posts_per_page' => -1
);
$query = new WP_Query( $query_args );
$term_ids = array();
if ( $query->have_posts() ) {
while ( $query->have_posts() ) {
$query->the_post();
// 获取当前文章关联的product_cat术语
$post_terms = get_the_terms( get_the_ID(), 'product_cat' );
if ( ! empty( $post_terms ) && ! is_wp_error( $post_terms ) ) {
foreach ( $post_terms as $post_term ) {
$term_ids[] = $post_term->term_id;
}
}
}
wp_reset_postdata();
}
// 去重后获取术语详情
if ( ! empty( $term_ids ) ) {
$unique_term_ids = array_unique( $term_ids );
$terms = get_terms( array(
'taxonomy' => 'product_cat',
'include' => $unique_term_ids,
'hide_empty' => false
) );
foreach ( $terms as $term ) {
echo '<p>关联分类:' . $term->name . '</p>';
}
}
?>
常见问题说明
获取不到术语的原因
- 分类法没有正确绑定到自定义文章类型,检查注册分类法时的
object_type参数是否正确填写了自定义文章类型名称 - get_terms参数中
hide_empty设置为true,而对应分类下没有关联任何已发布文章,此时可以调整为false查看是否有数据 - 分类法名称拼写错误,需要和注册时填写的分类法别名保持一致
术语排序设置
可以在get_terms参数中添加orderby和order参数控制排序,比如按名称升序排列:
<?php
$terms = get_terms( array(
'taxonomy' => 'product_cat',
'hide_empty' => false,
'orderby' => 'name', // 按名称排序
'order' => 'ASC' // 升序,DESC为降序
) );
?>
模板中直接调用示例
在自定义文章类型的归档模板或者详情模板中,可以直接调用函数输出当前文章的分类术语:
<?php
// 在product文章类型的详情页中输出当前文章的分类
$current_terms = get_the_terms( get_the_ID(), 'product_cat' );
if ( ! empty( $current_terms ) && ! is_wp_error( $current_terms ) ) {
echo '<p>当前文章所属分类:</p>';
foreach ( $current_terms as $current_term ) {
echo '<a href="' . get_term_link( $current_term ) . '">' . $current_term->name . '</a>';
}
}
?>
WordPress自定义文章类型分类术语get_termsWP_Query修改时间:2026-06-12 09:48:34