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

在Block中获取ACF分类选择并显示字段的问题与解决

WordPress分类ACF字段渲染问题及解决方案

问题背景

我在搭建网站时遇到了分类ACF字段渲染的问题:客户有一个名为ingredients的分类(Taxonomy),每个分类带有ACF图片字段和ACF描述字段。需要制作一个Block,允许选择特定配料分类并在页面上格式化渲染(无需链接到分类页),这样修改分类的描述或图片后,页面能自动同步更新。

按照ACF文档尝试了两段代码,但都无法正常渲染分类名称、原生描述及自定义ACF字段——仅能正确获取slug,页面能输出对应数量的<li>标签,但$term->name、the_field('description', $term)等内容都无法显示。直接调用the_field('ingredients_selector')能获取到分类ID,但就是拿不到分类名称和关联字段。

尝试过的代码

代码1

$terms = get_field('ingredients_selector');
if ( ! empty( $terms ) && ! is_wp_error( $terms ) ){
    echo '<ul class="ingredients-list">';
    foreach ( $terms as $term ) {
        echo '<li class="ingredients-list__item">' . $term->name . '</li>'; ?>
        <p>Description: <?php the_field('description', $term); ?></p>
        <p>Image: <?php the_field('image', $term); ?></p>
    <?php }
    echo '</ul>';
}
?>

代码2

<?php
$terms = get_field('ingredients_selector');
if( $terms ): ?>
<ul>
<?php foreach( $terms as $term ): ?>
<li>
<h2><?php echo esc_html( $term->name ); ?></h2>
<p>Term description: <?php the_field('description', $term); ?></p>
<p>Term Image: <?php the_field('image', $term); ?></p>
<p><?php echo esc_html( $term->description ); ?></p>
<a href="<?php echo esc_url( get_term_link( $term ) ); ?>">View all '<?php echo esc_html( $term->name ); ?>' posts</a>
</li>
<?php endforeach; ?>
</ul>
<?php endif; ?>

解决方案代码

<?php 
$tax = 'ingredients';

$terms = get_terms( $tax, $args = array(
  'hide_empty' => false, // 不隐藏空分类
));

foreach( $terms as $term ) {
    $term_link = get_term_link( $term );
    $image = get_field('image', 'ingredients_' . $term->term_id );
    $description = get_field('description', 'ingredients_' . $term->term_id );

    if( $term->count > 0 ) {
       echo '<a href="' . esc_url( $term_link ) . '">';
        echo '<img src="' . $image['url'] . '" alt="' . $image['alt'] .'">';       
        echo $term->name .'</a>';
        echo $description;

    } elseif( $term->count !== 0 ) {
        echo '' . $term->name .'';
    }
}
?>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 16:01:13