Page template query with WP_Query

I would like to query only pages with a certain page template with WP_Query or a function that would return the post object, but I can’t find any information about that on the official codex.

5

UPDATE:
This is now a decade old answer, meant for a very old version of WordPress. I can see the comments informing me that this might not work for newer WP versions, please do refer to the other answers below if mine is not working for your version of WP. For WP 2.*, this will work.

Try this…
Assuming the template name is ‘my_template.php’,

$query = new WP_Query(
    array(
        'post_type' => 'page',
        'meta_key' => '_wp_page_template',
        'meta_value' => 'my_template.php'
    )
);
//Down goes the loop...

You can also use get_posts, or modify query posts to get the job done. Both these functions use the same parameters as WP_Query.

Leave a Comment