Listing pages which uses specific template

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?

Read More

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.

Related posts

2 comments

  1. 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();
    
  2. 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…

Comments are closed.