get_template_part()调用自定义模板文件

目录

描述

get_template_part() 用来引用模板文件,类似于 get_header()get_sidebar()get_footer(),只不过这个 get_template_part() 可以引入自定义名字的文件。

  • 如果仅设置了 $slug 参数,则直接加载 {slug}.php 文件。
  • 如果同时设置了 $slug 和 $name 参数,则先尝试加载 {slug}-{name}.php 文件,如果找不到该文件,再去加载  {slug}.php 文件。比如,get_template_part( 'content', 'loop' );  表示如果content-loop.php存在,则调用content-loop.php,否则,就调用content.php
  • 如果无法正常加载,则会报错。

get_template_part() 描述

用法

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

get_template_part doesn't return a value and doesn't warn if it fails to find a matching template file.

If you want to hear about failures, use:

get_template_part() 用法

参数

$slug

(string) (必填) 模板别名

 值: None

$name

(string) (可选) 专   

 认值: None

get_template_part() 参数

示例

Using loop.php in child themes

Assuming the theme folder is wp-content/themes, that the parent theme is twentyten, and the child theme is twentytenchild, then the following code --

will do a PHP require() for the first file that exists among these, in this priority:

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

Using with theme subfolders

To use this function with subfolders in your theme directory, simply prepend the folder name before the slug. For example, if you have a folder called "partials" in your theme directory and a template part called "content-page.php" in that sub-folder, you would use get_template_part() like this:

Navigation

Adding a navigation bar to theme using a generic nav.php template file:

get_template_part() 示例

注意

Passing Variables to Template

Because the template is being required, it will not have access to any variables you define within the calling theme's PHP code, unless you explicitly declare them as global.

However, load_template(), which is called indirectly by get_template_part() extracts all of the WP_Query query variables, into the scope of the loaded template. So you can use set_query_var() to make your variable available to the template part.

get_template_part() 注意

历史

  • 添加于 版本: 3.0

get_template_part() 历史

源文件

get_template_part() 函数的代码位于 wp-includes/general-template.php.

get_template_part() 源文件

相关