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

如何将Gutenberg区块模板关联到页面并实现正常显示?

解决ACF + Gutenberg区块无法在页面显示的问题

1. 修复页面模板的核心问题

你的Home模板仅加载了页面头尾,没有输出Gutenberg编辑器中的内容(包含你添加的ACF区块),这是区块不显示的直接原因。修改模板代码如下:

/**
 * Template Name: Home
 *
 */

get_header(); ?>

<?php
// 循环输出当前页面的编辑器内容(包含ACF区块)
if ( have_posts() ) :
    while ( have_posts() ) : the_post();
        the_content();
    endwhile;
endif;
?>

<?php get_footer();

2. 确保ACF区块与模板文件正确关联

后台可视化配置方式

在ACF后台创建区块时,找到「渲染模板」选项,选择对应区块的模板路径,格式示例:template-parts/block/[你的区块文件夹名]/[区块模板文件名].php

代码注册区块方式(可选)

如果通过代码注册ACF区块,需在render_template参数中指定正确的模板路径:

add_action('acf/init', 'register_custom_acf_blocks');
function register_custom_acf_blocks() {
    if( function_exists('acf_register_block_type') ) {
        // 示例:注册一个自定义区块
        acf_register_block_type(array(
            'name'              => 'custom-hero',
            'title'             => 'Hero 横幅区块',
            'description'       => '首页顶部的Hero展示区块',
            'render_template'   => 'template-parts/block/custom-hero/block.php',
            'category'          => 'formatting',
            'icon'              => 'admin-comments',
            'keywords'          => array( 'hero', 'banner', '首页' ),
        ));
    }
}

3. 加载区块独立的CSS和JS

在主题的functions.php中添加代码,条件加载对应区块的资源(以首页为例):

add_action('wp_enqueue_scripts', 'enqueue_custom_block_assets');
function enqueue_custom_block_assets() {
    // 判断当前页面是否使用Home模板
    if (is_page_template('template-home.php')) {
        // 加载Hero区块的CSS
        wp_enqueue_style(
            'custom-hero-style',
            get_template_directory_uri() . '/template-parts/block/custom-hero/style.css',
            array(),
            filemtime(get_template_directory() . '/template-parts/block/custom-hero/style.css')
        );
        // 加载Hero区块的JS
        wp_enqueue_script(
            'custom-hero-script',
            get_template_directory_uri() . '/template-parts/block/custom-hero/script.js',
            array('jquery'),
            filemtime(get_template_directory() . '/template-parts/block/custom-hero/script.js'),
            true
        );
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 13:01:23