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

如何在WooCommerce商品页展示带标签和值的ACF自定义字段并隐藏空字段

你的原有代码存在两处核心问题:

  • 未调用ACF接口获取字段数据,所有用到的$guide_price、$field等变量均未定义
  • 代码结构冗余,后续新增字段需要重复编写判断逻辑,维护成本高

修正后的functions.php代码

add_action( 'woocommerce_after_single_product', 'property_overview_field', 3 );
function property_overview_field() {
    // 此处填入你所有ACF字段的名称,后续新增字段直接往数组里加即可
    $target_fields = [
        'guide_price',
        'property_category',
        'property_type',
        'bedroom',
        'bathroom',
        'listing_status',
        'city',
        'county',
        'location',
        'epc_rating'
    ];
    $has_valid_field = false;
    $output_html = '';

    foreach ($target_fields as $field_name) {
        // 获取ACF字段完整数据(包含标签、值等所有配置)
        $field = get_field_object($field_name);
        if (!$field || empty($field['value'])) continue;
        $has_valid_field = true;
        // 拼接单条字段HTML
        $output_html .= sprintf(
            '<li>%s:<strong>%s</strong></li>',
            esc_html($field['label']),
            esc_html($field['value'])
        );
    }

    // 只有存在有效字段时才输出整个区块
    if ($has_valid_field) {
        echo '<div class="property-overview"><ul>' . $output_html . '</ul></div>';
    }
}

调整后的CSS代码

你原有CSS仅需要去掉主题类前缀即可适配所有WooCommerce商品页:

.property-overview{margin: 0px 0px 30px 0px;padding: 0px;display: flex;}
.property-overview ul {background: #fff;box-shadow: 0 2px 4px rgba(0,0,0,.1);padding: 12px 20px !important; width: 100%;margin-top: 0; margin-bottom: 10px;list-style: none !important;}
.property-overview li {border-bottom: 1px dashed #ddd;clear: left;float: left;line-height: 40px; width: 48%;}
.property-overview ul li span{ font-weight:600;}
.property-overview li strong.emphasize {color: #666;font-weight: 600;}
.property-overview li strong{ float:right;}
.property-overview li:nth-child(2n) { float: right; clear: right;}

以上代码实现效果:

  • 自动读取ACF后台设置的字段标签,无需手动硬编码
  • 字段值为空时自动隐藏该条字段,不会输出空行
  • 两列网格布局,标签居左、值居右,和布局示例完全匹配
  • 后续新增字段仅需要在$target_fields数组中添加对应字段名即可,无需修改其他逻辑

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 12:45:06