How to get page by page template in WordPress

There are situations when you need to redirect users to (or get something from, do something with) a specific page which is created by a page template in WordPress such as a thank you page after submitting a form. Unfortunately there’s no official ways to get the page with a page template name in WordPress using get_posts() (or any query post) function. But with a small tip with meta query arguments, you can do that easily.

The trick here is page template is saved in page’s custom field (meta data) with name _wp_page_template. It’s a hidden custom field so you can’t view it in the Custom Field meta box. This meta stores the template file name of the page.

So, to get all pages by page template name in WordPress, you can do this query:

$pages = get_posts( array(
    'post_type' => 'page',
    'meta_key' => '_wp_page_template',
    'meta_value' => 'template-name.php', // Change this to your template file name
    'hierarchical' => 0,
) );

// Now you have all $pages
// Do something here

If you want to get only 1 page with page template name, just do this:

$page = get_posts( array(
    'post_type' => 'page',
    'meta_key' => '_wp_page_template',
    'meta_value' => 'template-name.php', // Change this to your template file name
    'hierarchical' => 0,
    'posts_per_page' => 1,
) );

if ( $page )
{
    $page = current( $page );
    // Do something here
}

That’s it! I write this because I often have to use this code in themes/plugins. I hope this quick tip can help you, too.

2 thoughts on “How to get page by page template in WordPress

Comments are closed.

Newsletter

Subscribe to our newsletter to receive news and tutorials about WordPress and web development.

Memory - An elegant, clean and powerful WordPress blog theme! Learn more →