# WordPress 函数get_template_part()使用介绍

> 来源：梦飞idc云平台 | 原文：https://www.mfisp.com/2291.html | 发布：2021-11-26 | 更新：2021-11-26 | 分类：建站教程

get_template_part() 函数用于调用自定义模板文件，也可以引入自定义名字的文件。使用get_template_part()函数，可以更灵活的控制主题，我觉得get_template_part()函数最大的好处就是大大的减少了代码的重写量。

 

我们知道，调用header.php可以用get_header()方法，调用footer.php可以用get_footer()方法，调用 sidebar.php可以用get_sidebar()方法，那么，调用自定义模板文件的时候，我们需要用get_template_part()函 数。这好比如原生的php也有require及include两种引入文件方法是一个道理。

 

为什么要自定义模板文件  
比如，分类页、标签页、作者页、甚至首页可能都需要用到一段共同的代码——如以摘要方式输出文章。那么，我们可以将这段代码放到content.php中，然后在分类、标签、和首页模板文件调用content.php，以减少代码重写量。

 

get_template_part()函数的使用很灵活，不仅仅是加载一个模板文件进来，而且还有备用的选项，调用代码如下：

 

## 语法结构

 

```
<?php get_template_part( $slug, $name ); ?>
```

 
 
- $slug (必须) 通用的模板名（字符串）要引入的模板的文件名，不包括后缀名 .php，也就是如果需要引入当前主题根目录的 content.php 文件 $slug 填写 ‘content’ 即可。 
- $name (可选) 指定的模板名（字符串）要引入的模板的文件的副文件名，如果要引入当前主题根目录的 content-nav.php 文件 $slug 参数填写 ‘content’，$name 参数填写 ‘nav’。 

 

## 使用实例

 

```
1、如果content-loop.php存在，则调用content-loop.php，否则，就调用content.php
<?php get_template_part( 'content', 'loop' ); ?>

2、引入当前主题根目录的 tags.php文件：
<?php get_template_part( 'tags' );  ?>

3、引入当前主题 inc 目录的 myfunctions.php 文件：
<?php get_template_part( 'inc/myfunctions' ); ?>

4、调用主题partials文件夹下content-page.php
<?php php get_template_part( 'partials/content', 'page' ); ?>
```

---
本页由 梦飞idc云平台（https://www.mfisp.com）提供。站点导航见 https://www.mfisp.com/llms.txt
