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

如何为WordPress所有页面设置统一基础模板并正确嵌入自定义内容

解决WordPress页面统一基础结构及自定义内容嵌入问题

问题根源

你当前的自定义模板逻辑存在错误:调用get_template_part('templates/page')会直接执行page.php的全部代码(包括get_header()、<main>容器、get_footer()),之后输出的“Test”和</div>自然会出现在footer之后,完全脱离了page-wrapper的结构范围。

正确实现方案

要让所有页面共享统一基础结构,同时让自定义模板的内容嵌入到page-wrapper内部,推荐以下两种可行方案:

方案1:拆分通用结构为模板部件(推荐)

把统一的基础结构拆分为独立的模板片段,自定义模板只需调用这些片段并填充专属内容。

  1. 创建通用模板部件
    在主题目录下新建templates文件夹,创建两个文件:

    • templates/header-base.php(基础头部结构):
      <?php get_header(); ?>
      <main>    
          <div class="page-wrapper">
      
    • templates/footer-base.php(基础尾部结构):
      </div>
      </main>
      <?php get_footer(); ?>
      
  2. 修改默认page.php
    让默认页面也适配统一结构:

    <?php
    get_template_part('templates/header-base');
    
    // 默认页面内容
    while (have_posts()) : the_post(); 
        the_content();
    endwhile; 
    
    get_template_part('templates/footer-base');
    ?>
    
  3. 编写自定义页面模板
    自定义模板可以轻松嵌入到统一结构中,比如你的测试模板:

    <?php /* Template Name: Test page template */
    get_template_part('templates/header-base');
    
    // 自定义页面内容
    echo 'Test';
    
    get_template_part('templates/footer-base');
    ?>
    

方案2:利用WordPress动作钩子

通过在基础结构中添加自定义钩子,让自定义模板向page-wrapper内部注入内容。

  1. 修改page.php为通用基础结构
    在page-wrapper内部添加自定义钩子:

    <?php get_header(); ?>
    <main>    
        <div class="page-wrapper">
            <?php
            // 自定义钩子,用于注入页面内容
            do_action('custom_page_content');
            
            // 默认页面内容(仅当无自定义钩子时显示)
            if (!did_action('custom_page_content')) {
                while (have_posts()) : the_post(); 
                    the_content();
                endwhile; 
            }
            ?>
        </div>
    </main>
    <?php get_footer(); ?>
    
  2. 编写自定义页面模板
    通过钩子向page-wrapper内部添加内容:

    <?php /* Template Name: Test page template */
    // 挂载钩子函数输出自定义内容
    add_action('custom_page_content', function() {
        echo 'Test';
    });
    
    // 加载基础结构的page.php
    get_template_part('page');
    ?>
    

效果验证

两种方案都能让自定义模板中的内容(比如“Test”)被正确包含在<div class="page-wrapper">内部,同时所有页面都保持你需要的统一基础结构。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 10:05:00