Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 504
nathanjosiah Avatar asked Oct 03 '11 03:10

nathanjosiah


2 Answers

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. ?>
like image 83
Robot Avatar answered Oct 16 '22 00:10

Robot


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!

like image 40
Berto Avatar answered Oct 15 '22 22:10

Berto