get_page_template_slug()WP 3.4.0

Gets the name of the PHP file that is set as the template for the specified post.

If a template for the post is not set, will get an empty string.

The template file name is stored in the meta-field _wp_page_template (wp_postmeta table). If the page template file is located in a subdirectory, then the value will be like:

folder-name/file-name.php

Custom fields that start with "_" are not displayed in the admin panel in the "custom fields" box. Such names are considered reserved in WordPress. Therefore in the admin panel you will not see the field that stores the template file.

No Hooks.

Returns

String|false.

  • String - The template file name.
  • Empty string - when no template is set for the page or its value equals "default".
  • false - when the post is not found.

Usage

$page_template_slug = get_page_template_slug( $post_id );
$post_id(int|WP_Post)
ID of the page or WP_Post object of the page to check. Default: the current post in the loop (global $post).
Default: null

Examples

0

#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 );
0

#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() code WP 6.9.1

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