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

- Link: https://yjyj.net/learn/wordpress-learn/6197.html
- Published: 2021-05-02T14:17:07+08:00
- Author: 小 虾

⚡ 生猛大蝦编辑部 · 30 秒核心看点

 * get_template_part() 可引入自定义模板文件，比 get_header() 更灵活。
 * slug 是必填主文件名，name 是可选副文件名，组合后可加载不同模板。
 * 示例覆盖根目录与子目录写法，适合做主题模块化拆分与复用。

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')。这样能把主题模板按功能分层，结构更清晰，也更方便维护。

📚 【[WordPress 学习](https://yjyj.net/category/learn/wordpress-learn)】专栏延伸
阅读与热门精选（[全站文章归档](https://yjyj.net/archive)）：

 * [极客族公共加速服务](https://yjyj.net/learn/wordpress-learn/6194.html)
 * [使用the_post_thumbnail_url()获取特色图片缩略图URL](https://yjyj.net/learn/wordpress-learn/6188.html)
 * [调用WordPress分类描述和去除WordPress分类描述P标签](https://yjyj.net/learn/wordpress-learn/6199.html)
 * [极致的Gravatar头像全球加速服务](https://yjyj.net/learn/wordpress-learn/6232.html)
 * 热门必读[重置 Mac 的 SMC](https://yjyj.net/learn/7596.html)
 * 热门必读[CSS 盒模型边界重叠 (Margin Collapse) 原理与解决方案](https://yjyj.net/css/3536.html)
