5ucms论坛

标题: WordPress 函数:get_template_part()调用你的自定义模板 [打印本页]

作者: admin    时间: 2021-5-23 17:09
标题: WordPress 函数: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
  1. get_template_part( 'content', 'loop' );
复制代码


2、引入当前主题根目录的 tags.php文件:
  1. get_template_part( 'tags' );
复制代码


3、引入当前主题 inc 目录的 myfunctions.php 文件:
  1. get_template_part( 'inc/myfunctions' );
复制代码


4、调用主题partials文件夹下content-page.php
  1. php get_template_part( 'partials/content', 'page' );
复制代码

源文件
get_template_part() 位于 wp-includes/general-template.php.


原文参考:http://codex.wordpress.org/Function_Reference/get_template_part




欢迎光临 5ucms论坛 (http://bbs.5ucms.com/) Powered by Discuz! X3.2