函数文档

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:

  1. {Page Template}.php
  2. page-{page_name}.php
  3. page-{id}.php
  4. page.php

An example of this is:

  1. page-templates/full-width.php
  2. page-about.php
  3. page-4.php
  4. 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

Return

string Full path to page template file.

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 );
}

Changelog

Version Description
4.7.0 The decoded form of page-{page_name}.php was added to the top of the template hierarchy when the page name contains multibyte characters.
1.5.0 Introduced.

User Contributed Notes