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 !!