
本文介绍正确在 WooCommerce 单商品页面描述区域之后插入 ACF 自定义字段(如 Download、Color)的方法,解决因错误使用 the_content 过滤器导致的 PHP 语法错误,并推荐使用更精准的 woocommerce_after_single_product_summary 动作钩子。
本文介绍正确在 woocommerce 单商品页面描述区域之后插入 acf 自定义字段(如 download、color)的方法,解决因错误使用 `the_content` 过滤器导致的 php 语法错误,并推荐使用更精准的 `woocommerce_after_single_product_summary` 动作钩子。
在 WooCommerce 开发中,若想在商品描述下方(即 woocommerce_after_single_product_summary 区域)安全展示 ACF 自定义字段内容,切勿直接在字符串中嵌入 PHP 标签(如原代码中的 <?php if(...): ?>),这会导致致命错误——因为 the_content 过滤器接收的是纯文本字符串,无法执行 PHP 逻辑。
✅ 正确做法是:改用 动作钩子(action hook),而非内容过滤器(filter)。WooCommerce 提供了语义清晰、位置精准的钩子,例如:
-
woocommerce_after_single_product_summary:位于商品主图、标题、价格、描述等摘要区块之后,非常适合追加结构化信息。
以下是推荐使用的完整、可直接部署的代码(请放入主题的 functions.php 或子主题中):
add_action( 'woocommerce_after_single_product_summary', 'misha_add_custom_info', 10 );
function misha_add_custom_info() {
// 确保仅在单商品页面执行(比 is_product() 更精确)
if ( ! is_singular( 'product' ) ) {
return;
}
// 开始输出 HTML(此时已处于 PHP 执行上下文中,可自由使用条件与模板函数)
?>
<div class="custom-product-info">
<table class="vertical-menu">
<tbody>
<tr>
<td class="cabecera">
<?php if ( get_field('download') ): ?>
<strong><i class="icon-checkmark"></i> Download:</strong>
<?php endif; ?>
</td>
<td class="detail">
<strong><?php the_field('download'); ?></strong>
</td>
</tr>
<tr>
<td class="cabecera">
<?php if ( get_field('color') ): ?>
<strong><i class="icon-checkmark"></i> Color:</strong>
<?php endif; ?>
</td>
<td class="detail">
<strong><?php the_field('color'); ?></strong>
</td>
</tr>
</tbody>
</table>
</div>
<?php
}? 关键改进说明:
- ✅ 使用
add_action()+woocommerce_after_single_product_summary,避免污染the_content,语义清晰、定位准确; - ✅ 移除所有字符串内联 PHP(如原
$content .= '<td> <?php ... ?>'),改用 PHP 输出块(<code>?>...<?php),确保语法合法; - ✅ 添加
is_singular('product')双重校验,比is_product()更健壮(尤其在 REST API 或缓存环境下); - ✅ 封装在
<div class="custom-product-info"> 中,便于后续 CSS 定制与样式隔离; <li>✅ 每个 <code>the_field()前均有对应if (get_field())判断,防止空值渲染冗余标签。 - 确保已安装并激活 Advanced Custom Fields (ACF) 插件,且字段名
download和color已正确定义于产品字段组; - 若使用 ACF Pro,请确认字段返回格式为「标准值」(非数组或对象),否则需调整
the_field()为get_field()并手动echo; - 强烈建议在子主题中添加该代码,避免主题更新时丢失修改;
- 如需控制显示顺序,可调整
add_action()的第 3 个参数(默认10),数值越小越靠前(如设为5会显示在默认“相关商品”之前)。
⚠️ 注意事项:
通过以上方式,你不仅能彻底规避语法错误,还能获得更稳定、可维护、符合 WooCommerce 最佳实践的扩展方案。

















