get_template_part()调用自定义模板|wordpress函数

  我们在用wordpress开发主题的时候,可能需要调用一段固定的代码比如左侧菜单,这段代码会在主页、栏目页、文章页用到,如果直接写入每个页面模板是没有问题,但是如果要改左侧菜单一个链接那就要改三次,很麻烦。能不能把左侧菜单写到一个模板里,然后通过函数来调用呢?可以的,我们知道php可以用include和require引入,在wordpress中已经有定义了get_template_part()函数,具有相同的作用。下面随ytkah一起来看看怎么使用吧

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

<?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' ); ?>

  我们一般喜欢把固定模板放在主题template-parts文件夹里,方便管理,建议这样操作,wordpress官方的模板都是如此。比如本例定义了一个/template-parts/menuleft.php,那我们就可以这样调用

<?php get_template_part( 'template-parts/menuleft' ); ?>

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

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

  5、(1的延伸)使用 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

  源文件: 

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

  参考资料:http://codex.wordpress.org/Function_Reference/get_template_part

 

posted @ 2019-07-18 09:29  ytkah  阅读(1002)  评论(0编辑  收藏  举报
IPO发家故事 网址导航 gg N / G Sitemap

部分内容来源于网络,如有版权问题请联系删除