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

如何用page.php统一所有页面模板并通过get_template_part调用内容

实现通用page.php模板,动态加载对应内容模块

没问题,这完全可以实现!咱们可以通过条件判断+get_template_part()的组合,让page.php成为所有页面的通用骨架,自动根据页面选择的模板加载对应的内容模块,彻底避免重复代码。

修改后的page.php代码

<?php get_header(); ?>
<main id="page-main" role="main" class="main">
    <?php
    // 检查当前页面是否使用了「文章展示」自定义模板
    if ( is_page_template( 'page-posts.php' ) ) {
        // 加载文章展示专用内容模板
        get_template_part( 'content', 'posts' );
    } else {
        // 默认加载灵活内容模板(未设置自定义模板时启用)
        get_template_part( 'content', 'flexible' );
    }
    ?>
</main>
<?php get_footer(); ?>

配套步骤:创建自定义页面模板文件

你需要新建一个名为page-posts.php的文件(放在主题根目录),用来作为后台页面的模板选项,内容只需要声明模板名称,其余逻辑完全复用page.php:

<?php
/*
Template Name: 文章展示页面
*/
// 直接调用通用page.php模板,不需要重复写header/main/footer
get_template_part( 'page' );

怎么用?

  • 在WordPress后台新建/编辑页面时,右侧「页面属性」里就能看到「文章展示页面」这个模板选项,选择它并发布;
  • 这个页面就会自动加载content-posts.php的内容;
  • 没选择自定义模板的页面,会默认加载content-flexible.php的内容。

补充说明

  • is_page_template('xxx.php')用来判断当前页面是否使用了指定的自定义模板,参数是模板文件的文件名;
  • get_template_part('content', 'posts')会自动加载content-posts.php文件,第二个参数是文件名的后缀部分;
  • 如果你以后需要新增其他页面模板,只需要重复两步:新建page-xxx.php声明模板名称,然后在page.php里加一个elseif(is_page_template('page-xxx.php'))的判断,加载对应的content-xxx.php即可,非常灵活。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 09:09:41