get_page_templates()
Gets all existing page templates of the current theme (active theme).
The function scans all theme files for the string Template Name: Template Name.
To work on the front end, you need to include the file:
require_once ABSPATH . '/wp-admin/includes/theme.php';
Instead of this function, it is sometimes more convenient to use the construct wp_get_theme()->get_page_templates(). Then there is no need to include the file.
However, the returned array is different - the keys and values are reversed. The key will be the file name, and the value will be the template name. See example 2.
No Hooks.
Returns
String[]. The keys of the array are the names of the page template, and the values are the names of the php file:
Array ( [Page Template Name] => page_template-file.php [Page Template Name 2] => page_template-file2.php )
Usage
$templates = get_page_templates();
- $post(WP_Post/null)
- The page being edited. Usually, this parameter is not specified.
Default: null - $post_type(string)
- The post type for which templates need to be retrieved. Since version 4.7.
Default: 'page'
Examples
By default, calling the function may cause an error. To make the function work, you need to include the file in which it is located:
include( ABSPATH . '/wp-admin/includes/theme.php' ); $templates = get_page_templates();
#1 Using the get_page_templates() method of the WP_Theme class
It's more convenient and correct to use get_page_templates() method instead of this function. In this case you don't need to include the necessary file:
$templates = wp_get_theme()->get_page_templates(); print_r( $templates );
Returns:
Array ( [my-custom-page.php] => My permanent page template [my-page-templates/my-second-page.php] => Another template for a permanent page )
As you see here, the key is the name of the file, and the value is the name of the template.
#2 Let's display the names of static page templates
Suppose we have 2 templates for static pages in our theme: "Archive Page" and "One Column, No Navigation Menu":
include( ABSPATH . '/wp-admin/includes/theme.php' ); $templates = get_page_templates(); print_r( $templates ); /* will return: Array ( [Archive page] => page_archive-template.php [One-column, no navigation menu] => page_one-column-template.php ) */
Now Display it:
foreach ( $templates as $template_name => $template_filename ) {
echo "$template_name ($template_filename)<br />";
}
/* Returns:
Archive page (page_archive-template.php)
One column, no navigation menu (page_one-column-template.php)
*/
Changelog
| Since 1.5.0 | Introduced. |
| Since 4.7.0 | Added the $post_type parameter. |
get_page_templates() get page templates code WP 7.0
function get_page_templates( $post = null, $post_type = 'page' ) {
return array_flip( wp_get_theme()->get_page_templates( $post, $post_type ) );
}