In a recent project, I had the need to get an array of all of the pages on a site that were using a particular page template. It turns out that this is really just an extension of any other type of meta query I could run, but you need to know that the meta field storing the info for the page template is in _wp_page_template.
I found a few examples of this using WP Query, but decided to write a quick little function using the get_pages function instead because it seemed cleaner for this use case then having to cleanup WP Query.
The function looks like this:
function get_page_by_template($template = '') { $args = array( 'meta_key' => '_wp_page_template', 'meta_value' => $template ); return get_pages($args); }
In my case, using get_pages
instead of the WP_Query
class make sense because of what I’ve trying to find, but I’d recommend checking out this article on the difference between WP_Query, get_posts, and get_pages for further reading on when you might want to use a specific strategy.
If your application doesn’t need to know what page templates are in use, and instead you just want to find out for other development related reasons, you could simply query the database from PHPMyAdmin:
SELECT p.post_title, pm.meta_value
FROM wp_posts p
LEFT JOIN wp_postmeta pm
ON p.ID = pm.post_id
WHERE p.post_status = “publish”
AND pm.meta_key = “_wp_page_template”
AND pm.meta_value != “default”
Thanks for sharing, this is a great way to grab that data straight from the DB if you don’t need to get it as a part of a WP template. Thanks for reading, Jeff
Thanks a lot !!
Thank you Brian Gottier for this query. I want to note that if you copy and paste this into PHPMyAdmin, you may get an error because the quotation marks copied from this website are special characters. Replacing them in the SQL query by typing the quotations (“) manually fixed this for me.
Thanks for pointing that out in case anyone runs into that issue – JE
I also wanted to point out that if one wants to search for all pages containing a specific template, the last line of Brian Gottier’s query can be changed so that instead of:
AND pm.meta_value != “default”
…we can use:
AND pm.meta_value = “my-template-file-name.php”
Here is the full query then:
SELECT p.post_title, pm.meta_value
FROM wp_posts p
LEFT JOIN wp_postmeta pm
ON p.ID = pm.post_id
WHERE p.post_status = “publish”
AND pm.meta_key = “_wp_page_template”
AND pm.meta_value = “my-template-file-name.php”
This was also a useful query for me based on Brian Gottier’s query:
How to get a list of all of the templates (excluding the default template) that are being used in your WP site:
SELECT DISTINCT t.meta_value FROM (
SELECT p.post_title, pm.meta_value
FROM wp_posts p
LEFT JOIN wp_postmeta pm
ON p.ID = pm.post_id
WHERE p.post_status = “publish”
AND pm.meta_key = “_wp_page_template”
AND pm.meta_value != “default”
) AS t