Get Template File Being Used on Current Page

How to Get Template File Being Used on Current Page

in Posts & pages
Google+ LinkedIn

Have you ever wanted to get template file being used on a current page? Well, I did, on a project I was working for a client. I wanted to get page template name to filter the post query based on the page template file being used. Although I could have done this by creating few template files for each page that I wanted to modify page query on, but it was not a perfect solution for the problem as well as not convenient if you have large number of pages on your website. I had to find a better way to do that to make sure it will also work on pages created in future too.

Lucky for me, WordPress automatically creates a meta key named “_wp_page_template” for each page that we create in WordPress and assign PHP template file name as its value. With this value we can easily get the name of the page template used for current page.

Here is a little code snippet that you can use in your theme files to return the name of the current page template being used. If you did not assign a template on a page then this meta key will return “default” as in default page template (page.php) is being used.

    // get template file being used on current page
    echo get_post_meta( $post->ID, '_wp_page_template', true );

Share the love

If you like this snippet, share it with others!

2 Replies on "Get Template File Being Used on Current Page"

  1. Svend Rugaard

    I have try this snippes but i cant see to find where to find the information i have look under “pages” but only normal overview.

    1. Hi Svend,

      Sorry for this issue, we forgot to echo the meta key.
      Please use updated code. It should be working now.

      Thanks :)

Leave a Reply

Your email address will not be published. Required fields are marked *