WordPress主题模板文件的引入方法

本文讲清 WordPress 主题模板文件如何用 get_template_part() 引入自定义模板,区分…


生猛大蝦 - abstract flight retro neon hyper warp space tunnel 3d illustration

get_template_part() 用来引用模板文件,类似于 get_header()、get_sidebar() 和 get_footer(),只不过这个 get_template_part() 可以引入自定义名字的文件。

使用方法: get_template_part( $slug, $name );

参数:
$slug(字符串)(必须)
要引入的模板的文件名,不包括后缀名 .php,也就是如果需要引入当前主题根目录的 loop.php 文件 $slug 填写 “loop” 即可。
默认:None
$name(字符串)(可选)
要引入的模板的文件的副文件名,如果要引入当前主题根目录的 loop-img.php 文件 $slug 参数填写 “loop”,$name 参数填写 “img”。
默认值:None
返回值: 此函数无返回值

例子:
引入当前主题根目录的 coocg.com 文件: get_template_part( 'coocg' );
引入当前主题 part 目录的 loop.php 文件: get_template_part( 'part/loop' );
引入当前主题根目录的 coocg-com.php 文件: get_template_part( 'coocg', 'com' );

此函数位于:wp-includes/general-template.php

❓ 延伸问答与排错指南(FAQ)
get_template_part() 和 get_header() 有什么区别?

get_header()、get_sidebar()、get_footer() 主要用于固定区域模板;get_template_part() 更灵活,可以按 slug 和 name 引入任意自定义模板片段,适合把主题拆成更细的模块复用。

get_template_part() 的 slug 和 name 怎么填?

slug 必填,写模板文件名但不带 .php 后缀;name 可选,用来拼出副文件名。比如引入 loop-img.php,可写成 get_template_part('loop','img'),系统会按这个组合去找对应模板。

子目录里的模板文件能直接引入吗?

可以,slug 里直接写路径即可。比如要引入 part 目录下的 loop.php,可写 get_template_part('part/loop')。这样能把主题模板按功能分层,结构更清晰,也更方便维护。