get_page_template_slug()
Gets the specific template name for a given post.
Gets the name of the php file, which is set as a template for the specified post. If the template for the post is not set empty string will be returned.
The name of the template file places in the _wp_page_template
meta field of wp_postmeta table. If the page template file is located in a subdirectory, the value will be as follows:
folder-name/file-name.php
Custom fields that start with "_" are not displayed in the admin panel in the "custom fields" block. Such names are considered service names in WordPress. Therefore, in the admin panel you will not see the field that stores post template file.
No Hooks.
Return
String|false
.
string
- Template file name.empty string
- when no template is set for the page or its value is "default".false
- when the post is not found.
Usage
get_page_template_slug( $post );
- $post(int|WP_Post)
- Post ID or WP_Post object.
Default: global $post
Examples
#1 Display the name of the template page 123
echo get_page_template_slug( 123 ); //> file-name.php
Or you can pass the WP_Post object - it will work a little faster that way:
$post = get_post( 123 ); // somewhere above in the code, we have already got the object, // now just pass it on echo get_page_template_slug( $post );
#2 Get all posts with a specified template file
If you want to find (get) all pages that work under a certain template file, you can do such query:
$template_filename = 'templates/offers.php'; $pages_with_template_filename = get_pages( [ 'meta_key' => '_wp_page_template', 'meta_value' => $template_filename ] );
This code will return (array|false) a list of pages matching the page template name.
It often happens that within the theme you are creating, you need to find a specific page that runs under a specific custom template, and that you need to dynamically access its ID, content, header, etc., this code will help you do that.
Changelog
Since 3.4.0 | Introduced. |
Since 4.7.0 | Now works with any post type, not just pages. |
get_page_template_slug() get page template slug code WP 6.6.2
function get_page_template_slug( $post = null ) { $post = get_post( $post ); if ( ! $post ) { return false; } $template = get_post_meta( $post->ID, '_wp_page_template', true ); if ( ! $template || 'default' === $template ) { return ''; } return $template; }