_wp_page_template to dynamically use template

First things first, never use query_posts, it overwrites the main query and can cause unwanted side-effects. Use WP_Query instead.

_wp_page_template is a post meta key, so the first thing we need to do is to load the value stored in that key for each page, using get_post_meta. That will give us the filename, which we can then try to load.

$this_page = get_queried_object_id();
$child_pages = new WP_Query(
    array(
        'post_type'=>'page',
        'posts_per_page' => -1,
        'post_parent' => $this_page,
        'orderby' => 'menu_order',
        'order' => 'ASC'
    )
);
if( $child_pages->have_posts() ){
    while( $child_pages->have_posts() ){
        $child_pages->the_post();

        // get the filename stored in _wp_page_template
        $template = get_post_meta( get_the_ID(), '_wp_page_template', true );

        // load the file if it exists
        locate_template( $template, true, false );

    }
    // restore the global $post after secondary queries
    wp_reset_postdata();
}

Leave a Comment