如何获取custom post type(自定义文章类型)的分类名称与分类ID
问题定位与修复方案
现有代码核心问题
- WP_Query参数配置错误:
taxonomy不是WP_Query的合法顶层参数,写在此处不会生效。如果不需要按自定义分类筛选文章,可直接删除该参数;如果需要仅筛选分配了manual_cat分类的文章,需要改用tax_query参数配置。 - 自定义分类数据获取逻辑错误:
get_post_field('cat_ID')仅能获取WordPress默认自带的category分类ID,无法读取自定义分类法manual_cat的ID、名称等数据,需要使用适配自定义分类的函数读取。 - 缺失查询重置逻辑:自定义WP_Query循环结束后未调用
wp_reset_postdata(),会污染全局post对象,导致后续其他循环逻辑异常。
修复后完整代码
$args = array( 'post_type' => 'manual', 'posts_per_page' => -1, // 如果你需要仅查询分配了manual_cat分类的文章,可放开下方tax_query配置 /* 'tax_query' => array( array( 'taxonomy' => 'manual_cat', 'operator' => 'EXISTS' ) ) */ ); $posts = new WP_Query($args); $usermanual = []; if ($posts->have_posts()): while ($posts->have_posts()): $posts->the_post(); $cat_info = []; // 获取当前文章关联的manual_cat分类数据 $terms = get_the_terms(get_the_ID(), 'manual_cat'); if (!is_wp_error($terms) && !empty($terms)) { // 取第一个关联分类,若需支持多分类可遍历$terms组装 $first_term = reset($terms); $cat_info = [ 'cat_id' => $first_term->term_id, 'cat_name' => $first_term->name ]; } $usermanual[] = array( 'ID' => get_the_ID(), 'title' => get_the_title(get_the_ID()), 'content' => get_post_field('post_content', get_the_ID()), 'slug' => get_post_field('post_name', get_the_ID()), 'Note' => get_field('_wp_footnotes', get_the_ID()), 'category' => $cat_info, // 包含分类ID和名称的数组 ); endwhile; // 重置全局post对象,避免后续逻辑异常 wp_reset_postdata(); endif;
关键逻辑说明
- 如果你需要返回所有关联的分类,只需遍历
$terms数组组装$cat_info即可,当前代码默认取第一个关联分类。 - 加入了错误判断,避免文章未分配任何
manual_cat分类时抛出PHP错误。
内容的提问来源于stack exchange,提问作者phplover
相关产品推荐
相关产品推荐

