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.

2 s
2

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();

Leave a Reply

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