语法结构
get_template_part( string $slug, string $name = null, array $args = array() )
参数详解
$slug (必须) 通用的模板文件名(字符串类型)也就是要引入的模板的文件名,不包括文件后缀”.php”;如果要引入当前主题目录下的 content.php 文件 $slug 参数填写 ‘content’ 即可。
$name (可选) 特定的模板文件名称(字符串类型),如果要引入当前主题根目录的 content-loop.php 文件 $slug 参数填写 ‘content’,$name 参数填写 ‘loop’。
该函数用于把一个局部模板文件载入到一个模板文件中。其实get_template_part();函数与使用get_header()、get_footer()和get_sidebar()几个函数非常类似,而get_template_part()函数的功能相比其他几个函数来说更加的强大。
get_template_part函数是在WordPress主题开发过程中的一个重要概念,通过使用该函数可以避免大量书写重复代码。如果多个模板文件需要使用很多相同的代码内容,我们可以将需要重复使用的代码内容保存到一个模板文件中,在需要使用此代码的地方,我们只需要使用get_template_part();函数调用该模板文件就可以了。
比如我们有两个php模板文件分别为content.php和index.php,我们要在index.php代码中调用content.php的代码内容。
index.php模板文件的代码:
/* Environment: We're in index.php */
if ( have_posts() ) :
while ( have_posts() ) : the_post();
get_template_part( 'content' );
endwhile;
endif;
content.php
局部模板文件的代码:
/* Environment: We're in content.php */
<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<h2 class="entry-title">
<a href="<?php the_permalink(); ?>">
<?php the_title(); ?>
</a>
</h2>
<?php the_excerpt(); ?>
</article>
执行规范
比如我们启用了子主题,并且在子主题模板文件中有如下代码:<?php get_template_part( ‘content’, ‘loop’ ); ?>
那么WordPress是怎样执行该段代码的呢?
- 在子主题中查询: content-loop.php
- 在父主题中查询: content-loop.php
- 在子主题中查询: content.php
- 在父主题中查询: content.php
参数示例
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' ); ?>
作者:牛奇网,本站文章均为辛苦原创,在此严正声明,本站内容严禁采集转载,面斥不雅请好自为之,本文网址:https://www.niuqi360.com/wordpress/wordpress-theme-how-to-use-get-template-part/