Using WordPress ‘get_page_template()’ PHP function

The get_page_template() WordPress PHP function retrieves the path of the page template in the current or parent template.


$template_path = get_page_template();


  • None

More information

See WordPress Developer Resources: get_page_template()

Note: For block themes, use locate_block_template() function instead.

The template hierarchy looks like:

  • {Page Template}.php
  • page-{page_name}.php
  • page-{id}.php
  • page.php


  • page-templates/full-width.php
  • page-about.php
  • page-4.php
  • page.php

The template hierarchy and template path are filterable via the {$type}_template_hierarchy and {$type}_template dynamic hooks, where $type is ‘page’.


Display Page Template Filename


echo '<!-- ' . basename( get_page_template() ) . ' -->';

Explanation: This code will display the filename of the page template used to render a page within an HTML comment.

Check if a Specific Template is Being Used


if ( 'page-about.php' === basename( get_page_template() ) ) {
    // Your code here

Explanation: This code checks if the current page is using the ‘page-about.php’ template. If true, the code inside the if statement will run.

Customize Content Based on Template


$template_name = basename( get_page_template() );

if ( 'page-about.php' === $template_name ) {
    // Custom content for the about page
} elseif ( 'page-contact.php' === $template_name ) {
    // Custom content for the contact page
} else {
    // Default content

Explanation: This code customizes the content based on the current page template. It checks for ‘page-about.php’ and ‘page-contact.php’, displaying custom content for each. If neither of those templates is used, it shows the default content.

Add a Body Class Based on Template


function my_body_class( $classes ) {
    $template_name = basename( get_page_template() );
    $classes[] = 'template-' . sanitize_html_class( $template_name, '' );
    return $classes;
add_filter( 'body_class', 'my_body_class' );

Explanation: This code adds a body class based on the current page template. The class name will be ‘template-‘ followed by the sanitized template name.

Display a Message for a Specific Template


$template_name = basename( get_page_template() );

if ( 'page-about.php' === $template_name ) {
    echo 'Welcome to the about page!';

Explanation: This code displays a welcome message only when the ‘page-about.php’ template is being used.