Web Dev Tid Bit (WDTB): Querying Pages By Template
Here is something I find myself looking up every now and then to get the syntax right / remember how to do. You may run in to a situation where you want to get a list of all pages that have a certain template in WordPress. There is a built in way for you to find these using the get_posts() function:
$args = array(
'posts_per_page' => -1,
'post_type' => 'page',
'post_status' => 'publish',
'meta_key' => '_wp_page_template',
'meta_value' => 'tpl-my-template.php'
$pages = get_posts($args);
This tells WordPress to “Get me all pages that have been published that use the tpl-my-template template. It is specifically looking for the meta_key of “_wp_page_template”, which all pages should have set. I’ve found use cases for this in places where I want to showcase certain top level pages, multiple galleries, etc. You can get a lot more specific with your query as well with things like looking only for pages with no parents, pages that have a specific meta field, pages that are also categorized with a specific tag, etc.