get_page_template()
云策文档标注
概述
get_page_template() 函数用于检索当前页面或父模板的页面模板路径。它遵循特定的模板层级,并可通过动态钩子进行过滤。
关键要点
- 函数返回页面模板文件的完整路径字符串。
- 对于区块主题,建议使用 locate_block_template() 函数替代。
- 模板层级包括:{Page Template}.php、page-{page_name}.php、page-{id}.php、page.php。
- 支持通过 '$type_template_hierarchy' 和 '$type_template' 动态钩子($type 为 'page')过滤模板层级和路径。
- 内部调用 get_query_template() 来获取模板。
代码示例
<!-- 显示用于渲染页面的模板文件名(在 HTML 注释中打印) -->
<?php echo '<!-- Template: ' . get_page_template() . ' -->'; ?>注意事项
- 在 Gutenberg 全站编辑中,此函数可能无效或返回 /wp-includes/template-canvas.php。
- 当页面名称包含多字节字符时,解码后的 page-{page_name}.php 会添加到模板层级顶部(自 4.7.0 版本起)。
原文内容
Retrieves path of page template in current or parent template.
Description
Note: For block themes, use locate_block_template() function instead.
The hierarchy for this template looks like:
- {Page Template}.php
- page-{page_name}.php
- page-{id}.php
- page.php
An example of this is:
- page-templates/full-width.php
- page-about.php
- page-4.php
- page.php
The template hierarchy and template path are filterable via the ‘$type_template_hierarchy’ and ‘$type_template’ dynamic hooks, where $type is ‘page’.
See also
Source
function get_page_template() {
$id = get_queried_object_id();
$template = get_page_template_slug();
$pagename = get_query_var( 'pagename' );
if ( ! $pagename && $id ) {
/*
* If a static page is set as the front page, $pagename will not be set.
* Retrieve it from the queried object.
*/
$post = get_queried_object();
if ( $post ) {
$pagename = $post->post_name;
}
}
$templates = array();
if ( $template && 0 === validate_file( $template ) ) {
$templates[] = $template;
}
if ( $pagename ) {
$pagename_decoded = urldecode( $pagename );
if ( $pagename_decoded !== $pagename ) {
$templates[] = "page-{$pagename_decoded}.php";
}
$templates[] = "page-{$pagename}.php";
}
if ( $id ) {
$templates[] = "page-{$id}.php";
}
$templates[] = 'page.php';
return get_query_template( 'page', $templates );
}
Skip to note 4 content
Codex
Display the filename of the page template used to render a page (printed within an HTML comment, in this example) :
Skip to note 5 content
speedy_snail
The link for $type_template is not found on this page. It needs updating.
Skip to note 6 content
thomask
this function is probably useless / not working as intended with Gutenberg Full Site Edit, as it returns /wp-includes/template-canvas.php