Find All WordPress Pages Using a Specific Page Template with WP_Query

Get all pages that use a specific template

We have a big site and a task to edit a page template. After the change we need to check all pages that use it, and a template may be used by many pages. So we need links to all of them. How can it be done? See below.

Problem: How to get the IDs of all pages that use a specific template?

Solution: WordPress stores the template of a page in the post meta _wp_page_template, as the path relative to the theme folder (for example pages/tpl-our-impact.php). So a normal WP_Query by this meta field is enough. Let’s write a simple function:

<?php
function get_pages_ids_that_use_template( $template_path ) {
    $query = new WP_Query( array(
        'post_type'      => 'page',
        'post_status'    => 'any',
        'posts_per_page' => -1,
        'fields'         => 'ids',
        'no_found_rows'  => true,
        'meta_key'       => '_wp_page_template',
        'meta_value'     => $template_path, // e.g. 'pages/tpl-our-impact.php'
    ) );

    return $query->posts;
}

With 'fields' => 'ids' the query returns only an array of IDs, which is enough here and much lighter than full post objects.

If you need links, output them with the IDs:

<?php
$pages_ids = get_pages_ids_that_use_template( 'pages/tpl-our-impact.php' );

echo '<h3>Pages with this template:</h3><ul>';
foreach ( $pages_ids as $page_id ) {
    echo '<li><a href="' . esc_url( get_permalink( $page_id ) ) . '">' . esc_html( get_the_title( $page_id ) ) . '</a></li>';
}
echo '</ul>';

The same in phpMyAdmin, without any code:

SELECT p.ID, p.post_name, p.post_status
FROM wp_posts p
JOIN wp_postmeta m ON m.post_id = p.ID AND m.meta_key = '_wp_page_template'
WHERE p.post_type = 'page' AND m.meta_value = 'pages/tpl-our-impact.php';

NOTE: Pages with the default template have the value default or no meta at all. If nothing is found, check the exact value with get_post_meta( $page_id, '_wp_page_template', true ) on a page you know uses the template.