
本文详解在基于 Block Theme(如 Twenty Twenty-Two)的子主题中,通过模板文件或短代码安全、可靠地显示 Advanced Custom Fields(ACF)值,解决模板修改被古腾堡编辑器覆盖、the_field() 无效等常见问题。
本文详解在基于 block theme(如 twenty twenty-two)的子主题中,通过模板文件或短代码安全、可靠地显示 advanced custom fields(acf)值,解决模板修改被古腾堡编辑器覆盖、`the_field()` 无效等常见问题。
WordPress 块主题(如 Twenty Twenty-Two)默认启用全站点编辑(FSE),其单页渲染逻辑与传统主题有本质区别:即使你创建了 single-myCustomPostType.php,若该自定义文章类型启用了“块模板”(Block Template),WordPress 会优先使用 templates/single-myCustomPostType.html(即 HTML 格式的块模板),而非 PHP 模板文件。这正是你遇到“修改 PHP 模板不生效”“保存编辑器后 HTML 模板被覆盖”的根本原因。
✅ 正确方案一:在块模板(HTML)中安全调用 ACF 字段
FSE 主题中的 .html 模板不支持原生 PHP,但可通过 wp:post-field 块或 wp:acf/field(需插件支持)间接输出——更推荐且兼容性最佳的方式是:使用 ACF 官方支持的 wp:shortcode 块嵌入自定义短代码。
-
在子主题的
functions.php中注册短代码:// functions.php function acf_custom_field_shortcode($atts) { $atts = shortcode_atts([ 'field' => '', 'post_id' => false, ], $atts); // 若未指定 post_id,自动获取当前主循环文章 ID $post_id = $atts['post_id'] ?: get_the_ID(); // 安全获取字段值(避免空字段报错) $value = get_field($atts['field'], $post_id); return !empty($value) ? esc_html($value) : ''; } add_shortcode('acf_field', 'acf_custom_field_shortcode'); 在编辑器中插入短代码块:
在自定义文章类型的编辑页面 → 点击「+」→ 搜索「短代码」→ 插入 → 输入:[acf_field field="mycustomfield"]
即可动态显示当前文章的mycustomfield值。
⚠️ 注意:确保 ACF Pro 已激活(免费版不支持
get_field()在非主循环上下文的稳定调用),且字段名称拼写完全一致(区分大小写)。
✅ 正确方案二:强制回退到 PHP 模板(适用于需复杂逻辑场景)
若必须使用 PHP 渲染(如需条件判断、循环嵌套、HTML 结构控制),请禁用该文章类型的块模板:
-
在子主题根目录创建
functions.php(若尚无),添加:// 禁用自定义文章类型的块模板,强制使用 PHP 模板 add_filter('use_block_editor_for_post_type', function($use_block_editor, $post_type) { if ($post_type === 'myCustomPostType') { return false; // 关闭古腾堡编辑器,启用经典编辑器 + PHP 模板 } return $use_block_editor; }, 10, 2); -
确保模板文件为
single-myCustomPostType.php(注意是.php,非.htm),并在其中安全调用:<?php // single-myCustomPostType.php get_header(); if (have_posts()) : while (have_posts()) : the_post(); ?> <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>> <h1><?php the_title(); ?></h1> <div class="entry-content"> <?php the_content(); ?> <!-- 安全输出 ACF 字段 --> <?php if (function_exists('the_field')): ?> <div class="acf-custom-field"> <strong>自定义字段:</strong> <?php the_field('mycustomfield'); ?> </div> <?php endif; ?> </div> </article> <?php endwhile; endif; get_footer();
? 关键总结
-
不要混用
.html(块模板)与 PHP 函数:FSE 下.html模板无法执行<?php the_field() ?>,必须通过短代码或get_field()+ 前端 JS(不推荐)实现。 - 短代码是 FSE 环境下的黄金方案:灵活、安全、可复用,且不受编辑器覆盖影响。
-
调试技巧:在模板中临时加入
<?php error_log(print_r(get_fields(), true)); ?>查看所有字段是否加载成功(需开启 WP_DEBUG)。 -
性能提示:避免在循环中多次调用
get_field();如需多个字段,建议一次get_fields()获取全部数组再提取。
遵循以上任一方案,即可稳定、专业地在自定义文章类型单页中呈现 ACF 数据,彻底告别模板失效与字段空白问题。


















