---
title: "WordPress主题模板文件的引入方法"
url: "https://yjyj.net/learn/wordpress-learn/6197.html"
author: "小 虾 (生猛大蝦编辑部)"
published_at: "2021-05-02T14:17:07+08:00"
updated_at: "2025-01-19T23:04:21+08:00"
categories: "WordPress 学习"
tags: "wordpress, WordPress优化, WordPress开发, 引入文件, 模板"
summary: "本文讲清 WordPress 主题模板文件如何用 get_template_part() 引入自定义模板，区分 slug 与 name 两个参数，并通过根目录与子目录示例说明实际写法。适合想拆分主题结构、复用模板片段的开发者快速上手，少踩文件命名和路径坑。"
source: "生猛大蝦 (https://yjyj.net)"
---

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

> 来源：[生猛大蝦 (yjyj.net)](https://yjyj.net/learn/wordpress-learn/6197.html) · 作者：小 虾 · 发布时间：2021-05-02

## 30 秒核心看点 (TL;DR)

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

---
更多 Linux 运维、WordPress 性能优化、前端工程化、Shopify 独立站与极客折腾指南：[生猛大蝦全站文章归档 (https://yjyj.net/archive)](https://yjyj.net/archive)
