Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

This question already has an answer here:

I have created a template named product.php with the following header:

<?php
/*
Template Name: Product Page
*/

How can I list, in a sidebar, every page that uses the "Product Page" template?

I have tried reading the wp_list_pages() function documentation, but it only seemed possible to list filtering by post_type, not by template used.

share|improve this question

marked as duplicate by toscho Sep 20 '13 at 21:03

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

add comment

2 Answers 2

up vote 0 down vote accepted

You can do this with a WP_Query meta_query. The page template filename is stored in post meta under the key _wp_page_template:

$args = array(
    'post_type' => 'page',
    'posts_per_page' => -1,
    'meta_query' => array(
        array(
            'key' => '_wp_page_template',
            'value' => 'product.php'
        )
    )
);
$the_pages = new WP_Query( $args );

if( $the_pages->have_posts() ){
    while( $the_pages->have_posts() ){
        $the_pages->the_post();
        the_title();
    }
}
wp_reset_postdata();
share|improve this answer
    
You beat me by 47 seconds! –  G. M. Sep 20 '13 at 21:01
    
... and someone beat us by a couple of years ;-) –  G. M. Sep 20 '13 at 21:04
add comment

the page template is setted via a meta field with the key '_wp_page_template'. The value for this meta field is the php full file name of the template file, something like

'page-products.php'

so you can create a custom function to easyly get the page with a specific template using meta_key and meta_value param off get_pages (or using a WP_Query with 'meta_query' argument):

get_pages_by_template( $template = '', $args = array() ) {
  if ( empty($template) ) return false;
  if ( strpos($template, '.php') !== (strlen($template) - 4) )  $template .= '.php';
  $args['meta_key'] = '_wp_page_template';
  $args['meta_value'] = $template;
  return get_pages($args);
}

This function accepts as first (mandatory) argument the template and as second (optional) argument all the arguments of get_pages.

the template can passed with or without '.php' extension:

$pages = get_pages_by_template('page-products');

or

$pages = get_pages_by_template('page-products.php');

After that, you can use the page retrieved as you want: loop throu them and output some markup, create a custom widget that make use of the function, and so on...

share|improve this answer
add comment

Not the answer you're looking for? Browse other questions tagged or ask your own question.