A-A+

WordPress中模板(文件)引用函数get_template_part()

2020年01月05日 建站经验 阅读 441 views 次

在WordPress中函数get_template_part()用来引用自定义的模板或PHP文件,函数的格式如下:

<?php 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

<?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、在子主题里面 使用 loop.php 。假设主题文件夹wp-content/themes下父主题是twentyten子主题twentytenchild,那么下面的代码:

<?php get_template_part( 'loop', 'index' ); ?>

php 的require()函数将按下面优先级包含文件

1. wp-content/themes/twentytenchild/loop-index.php
2. wp-content/themes/twentytenchild/loop.php
3. wp-content/themes/twentyten/loop-index.php
4. wp-content/themes/twentyten/loop.php

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

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

个人公众号“数字化设计CAX联盟”,欢迎关注,共同交流
标签:
为您推荐:

给我留言

© 坐倚北风 版权所有 严禁镜像复制 苏ICP备15034888号. 基于 Ality 主题定制 AliCMS
联系邮箱:leanwind@163.con,微信公众号:数字化设计CAX联盟

用户登录

分享到: