nathanjosiah
nathanjosiah

Reputation: 4459

Querying pages in WordPress by template name

I have a template named "Foo" in "foo.php", I would like to be able to select all pages that are using that template. I have searched for awhile now but have not been able to find a successful way to do this... Can somebody enlighten me on the proper/only way to do this?

Upvotes: 13

Views: 13918

Answers (3)

Berto
Berto

Reputation: 138

Robot's answer is good, but I thought I'd clarify a few things.

First, You should use the variable for the query you created, so it would be $query->have_posts() etc.

Second, you should specify post_type. I used any, so that it will pull any post types except for revisions.

Last, if this is in a page with any other WP loops, you may want to use wp_reset_query. I added one below and one above just in case, but you only really need this if you have another loop above or below. Remove it if you don't.

Here is the code:

wp_reset_query();
$query = new WP_Query( array(
    'post_type'  => 'any',
    'meta_key'   => '_wp_page_template',
    'meta_value' => 'foo.php'
) );

if ( $query->have_posts() ) {
    while ( $query->have_posts() ) : $query->the_post(); // WP loop
        the_title();
    endwhile; // end of the loop.
} else { // in case there are no pages with this template
    echo 'No Pages with this template';
}
wp_reset_query();

Hope that helps someone!! Happy coding!

Upvotes: 8

Jessie Baltazar
Jessie Baltazar

Reputation: 91

This also works

$pages = get_pages(

     array(

    'meta_key' => '_wp_page_template',

    'meta_value' => 'template.php'
       )
);

foreach($pages as $page){
    echo $page->post_title.'<br />';
}

http://jorgepedret.com/old/web-development/get-pages-by-template-name-in-wordpress/

Upvotes: 5

Robot
Robot

Reputation: 540

You can get this by using following code

$query = new WP_Query( array( 'meta_key' => '_wp_page_template', 'meta_value' => 'foo.php' ) );

if ( have_posts() ) while ( have_posts() ) : the_post();
<?php the_title(); ?>
<?php endwhile; // end of the loop. ?>

Upvotes: 11

Related Questions