You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ACF Taxonomy为空/值为null:自定义视频文章类型分类显示异常求助

问题解决:ACF分类法字段无法正常显示分类及链接

可能的问题及对应解决代码

场景1:在单篇视频文章模板(single-videos.php)显示当前文章关联的分类

如果你的代码是放在单篇视频页面,先确认ACF字段设置:字段类型为「分类法」,选择names分类法,返回格式设为「术语对象」。然后使用以下修正后的代码(兼容单选/多选字段):

<?php 
$terms = get_field('names');
// 处理单选字段返回单个对象的情况,转为数组统一遍历
if( is_object($terms) ) {
    $terms = array($terms);
}
if( $terms && !empty($terms) ): ?>
    <ul>
    <?php foreach( $terms as $term ): ?>
        <li>
            <h2><?php echo esc_html( $term->name ); ?></h2>
            <p><?php echo esc_html( $term->description ); ?></p>
            <a href="<?php echo esc_url( get_term_link( $term, 'names' ) ); ?>">查看所有「<?php echo esc_html( $term->name ); ?>」视频</a>
        </li>
    <?php endforeach; ?>
    </ul>
<?php endif; ?>

场景2:在归档页/其他页面显示names分类法下所有分类

如果是要展示整个分类法下的所有分类(关联视频文章),不要用get_field,直接用get_terms获取分类数据:

<?php
// 获取关联videos文章类型的names分类,仅显示有内容的分类
$terms = get_terms( array(
    'taxonomy' => 'names',
    'hide_empty' => true,
    'object_type' => array('videos')
) );

if( !empty($terms) && !is_wp_error($terms) ): ?>
    <ul>
    <?php foreach( $terms as $term ): ?>
        <li>
            <h2><?php echo esc_html( $term->name ); ?></h2>
            <p><?php echo esc_html( $term->description ); ?></p>
            <a href="<?php echo esc_url( get_term_link( $term, 'names' ) ); ?>">查看所有「<?php echo esc_html( $term->name ); ?>」视频</a>
        </li>
    <?php endforeach; ?>
    </ul>
<?php endif; ?>

额外排查步骤

  1. 确认分类法注册正确性:检查主题functions.php中的分类法注册代码,确保object_type包含videos:
function register_names_taxonomy() {
    $args = array(
        'label' => '名称',
        'public' => true,
        'show_ui' => true,
        'show_in_rest' => true,
        'hierarchical' => false // 按需设置层级
    );
    register_taxonomy( 'names', 'videos', $args );
}
add_action( 'init', 'register_names_taxonomy' );
  1. ACF字段设置验证:在ACF字段编辑页,确认「分类法」选择的是names,「返回格式」为「术语对象」。

内容的提问来源于stack exchange,提问作者alib0ng0

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 13:35:24