当前位置:K88软件开发文章中心编程全书编程全书02 → 文章内容

wordpress开发 – get_template_part()函数

减小字体 增大字体 作者:佚名  来源:网上搜集  发布时间:2019-1-4 9:20:28

-->

【函数介绍】

wordpress在3.0之后增加了调用指定模板到当前模板的函数get_template_part(),这样我们就可以很方便的将模板的公工部分提取出来共用,从而避免大量编写重复的代码,并且对于子主题,通过get_template_part()函数可以很容易的替换父主题的代码段。
包含了的模板文件由两部分组成,{slug}模板的短标记,{name}主模板的名称。
模板命名规则:”{slug}-{name}.php”.

【函数用法】

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

【参数说明】

$slug
(string) (必须) 模板别名.
Default: None
$name
(string) (可选) wordpress专用模板名称.
Default: None

【实例应用】

<div id="container"><div id="content" role="main"><?php/*  * 调用loop-single.php模板文件 */get_template_part( 'loop', 'single' );?></div><!-- #content --></div><!-- #container -->

假设主题文件夹wp-content/themes下父主题是twentyten子主题twentytenchild,那么PHP 的 require() 函数加载模板的顺序如下:

wp-content/themes/twentytenchild/loop-index.phpwp-content/themes/twentyten/loop-index.phpwp-content/themes/twentytenchild/loop.phpwp-content/themes/twentyten/loop.php

如果你将公用模板放置于某个目录下,比如调用主题partials文件夹下content-page.php,代码如下:

<?php get_template_part( 'partials/content', 'page' ); ?>

导航条的添加:

<?php get_template_part( 'nav' );           // Navigation bar (nav.php) ?><?php get_template_part( 'nav', '2' );      // Navigation bar #2 (nav-2.php) ?><?php get_template_part( 'nav', 'single' ); // Navigation bar to use in single pages (nav-single.php) ?>

【源文件】

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


wordpress开发 – get_template_part()函数