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

如何在分类术语foreach循环中调用ACF字段?代码故障求助

修复ACF分类特色图片显示问题

你的代码存在两个核心问题:

  • 循环外提前获取的$image仅对应当前页面的分类,无法匹配循环中的每个分类
  • $term_link变量未定义,导致分类跳转链接失效

以下是修正后的完整代码:

<?php
$size = 'full'; // (thumbnail, medium, large, full 或自定义尺寸)

foreach ( get_categories( [ 
    'orderby' => 'name',
    'order'   => 'ASC',
    'hide_empty' => 1,
    'exclude' => array(1)
] ) as $category ) { 
    // 针对当前循环的分类获取ACF字段
    $image = get_field('category_featured_image', 'category_' . $category->term_id);
    
    if( $image ) : 
        echo wp_get_attachment_image( $image, $size, "", ["class" => "category-feature-image"] );
    endif;
?>

<h2 class="category-snippet__title"><?php echo $category->name; ?></h2>
<p class="category-snippet__description"><?php echo $category->description; ?></p>
<a class="category-snippet" href="<?php echo esc_url( get_category_link($category) ); ?>"><?php esc_html_e('Learn more', 'pluto'); ?></a>

<?php
}
?>

关键修改说明:

  1. ACF字段匹配逻辑:将get_field移到循环内部,使用'category_' . $category->term_id作为参数,确保每个分类都能获取到自己的特色图片(ACF针对分类字段的参数格式为分类名_分类ID)
  2. 修复跳转链接:用get_category_link($category)生成正确的分类URL,并用esc_url进行安全转义
  3. 代码结构优化:将固定的$size定义保留在循环外,避免重复定义

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 13:40:36