首页>文档>WP函数>get_template_part自定义模板

此组别内的文章

需要支持?

如果通过文档没办法解决您的问题,请提交工单获取我们的支持!

get_template_part自定义模板

 

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()函数用法

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

  1. get_template_part( $slug, $name );

参数:

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

示例

1、如果content-loop.php存在,则调用content-loop.php,否则,就调用content.php

get_template_part( 'content', 'loop' );

2、引入当前主题根目录的 tags.php文件:

get_template_part( 'tags' );

3、引入当前主题 inc 目录的 myfunctions.php 文件:

get_template_part( 'inc/myfunctions' );

4、调用主题partials文件夹下content-page.php

php get_template_part( 'partials/content', 'page' );

源文件

get_template_part() 位于 wp-includes/general-template.php.
原文参考:http://codex.wordpress.org/Function_Reference/get_template_part

0 条回复 A文章作者 M管理员
    暂无讨论,说说你的看法吧
个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索