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.

🔥 HOT: Interested in boosting your WordPress SEO? My Slim SEO plugin is a super lighweight and automated plugin that handles most the hard work for you: meta tags, sitemap, redirection, schema & link building.

👉 Have a look and you will love it: wpslimseo.com

Leave a Reply

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

Copyright © 2024 Deluxe Blog Tips. All rights reserved.

My products: Meta Box | Slim SEO