函数文档

get_page_templates()

💡 云策文档标注

概述

get_page_templates() 函数用于获取当前主题中可用的页面模板。它通过扫描主题文件中的“Template Name”注释来识别模板,并返回一个以模板标题名称为键、文件名为值的数组。

关键要点

  • 函数参数:$post(可选,WP_Post 对象或 null,默认为 null)提供编辑的帖子上下文;$post_type(可选,字符串,默认为 'page')指定要获取模板的帖子类型。
  • 返回值:返回一个字符串数组,键为模板标题名称,值为模板文件名。
  • 依赖关系:内部调用 wp_get_theme()->get_page_templates() 方法,基于 WP_Theme 类实现。
  • 版本变更:从 WordPress 4.7.0 开始添加了 $post_type 参数,最初在 1.5.0 版本引入。

代码示例

$templates = get_page_templates();
print_r( $templates );

📄 原文内容

Gets the page templates available in this theme.

Parameters

$postWP_Post|nulloptional
The post being edited, provided for context.

Default:null

$post_typestringoptional
Post type to get the templates for. Default 'page'.

Return

string[] Array of template file names keyed by the template header name.

More Information

The function searches all the current theme’s template files for the commented “Template Name: name of template”. See also wp_get_theme() and the wp_get_theme() ->get_page_templates() method of the WP_Theme class.

Source

function get_page_templates( $post = null, $post_type = 'page' ) {
	return array_flip( wp_get_theme()->get_page_templates( $post, $post_type ) );
}

Changelog

Version Description
4.7.0 Added the $post_type parameter.
1.5.0 Introduced.

User Contributed Notes

  1. Skip to note 2 content

    Output a list of available templates

    The following code snippet loops through the available page templates and outputs their template names and the filenames.

    get_page_templates();
    print_r( $templates );
    ?>

    Returns:

    Array (
    	[template-contact.php] => Contact
    	[template-landing-page.php] => Landing Page
    	[template-another-template.php] => Another Template
    )