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?
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. ?>
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With