List All Pages Using a Particular Template in WordPress

If you have ever wanted to list all pages using a template in your WordPress site or theme, there is a relatively simple way that makes use of one of WordPress’ hooks.

I recently finished a new responsive WordPress theme for Rainbow Glass Studios, and when it came to building a sitemap I decided to split the list of pages into categories. This client not only works using a range of techniques, but they also run classes and workshops in glass-making, and showcase some of their student’s work. I could have used the standard wp_list_pages(); function but this would have just given me a straight list of the pages, even if I put in some conditions to make sure it was only published pages etc. Instead, I wanted to separate out the classes, techniques and student work from the ‘standard’ pages. These all used different templates in the site theme, so I needed to list all pages using a template – a couple of times.

How to list all pages using a template in your theme

What I did was create variations of this code (below) with headings to break up the content. Here it is then:

<?php $classpages = get_pages(array(
‘meta_key’ => ‘_wp_page_template’,
‘meta_value’ => ‘classes.php’
));
foreach($classpages as $classpage){
echo ‘<a href=”‘ . get_page_link($classpage->ID) . ‘”>’ . esc_html($classpage->post_title) . ‘</a>’ . ‘<br />’;
}
?>

All you need to change is the classpages/classpage references and the name of your particular page template file. The standard pages that use the page.php template were added to the sitemap manually.

You can see the finished Rainbow Glass Studios sitemap here.

other page


What do you think?

It's good to talk!

Your email address will not be published. Required fields are marked *