WordPress.org

Ready to get started?Download WordPress

Codex

Attention Interested in functions, hooks, classes, or methods? Check out the new WordPress Code Reference!

zh-cn:调用模板部分/get template part

Contents

描述

装载另外一个模板的部分代码到当前模板(区别于header, sidebar, footer)。使得当前主题可以更加容易的重用代码段,并且对于子主题,通过此函数可以容易的替换父主题的代码段。

Includes the named template part for a theme or if a name is specified then a specialized part will be included. If the theme contains no {slug}.php file then no template will be included.

作为参数,文件名格式 "{slug}-{name}.php".

用法

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

参数

$slug
(string) (required) The slug name for the generic template.
Default: None
$name
(string) (optional) The name of the specialized template.
Default: None

示例

在子主题中调用 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

导航条

向主题中添加导航条:

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

source: wp-tricks.co.il - using get_template_part() to create generic navigation bar

Notes

Change Log

Source File

get_template_part() is located in wp-includes/general-template.php.

Related

Include Tags

See also index of Function Reference and index of Template Tags.