I’m wondering if it is at all possible to set display a page template chosen by the user within the context of a query_posts
using get_template_part
. In other words, I have set up a page template to pull all of it’s child pages and display them, but I need each child page to display according to the page template that is chosen in the page editor. Is there any way to make that happen? Here is the code I have for the parent page template so far.
<?php
$this_page=get_query_var('page_id');
query_posts( array('post_type'=>'page', 'posts_per_page' => -1, 'post_parent' => $this_page, 'orderby' => 'menu_order', 'order' => 'ASC') );
if(have_posts()): while(have_posts()): the_post();
?>
<?php get_template_part('_wp_page_template'); ?>
<?php endwhile; endif; ?>
So, as you can see, I’ve got the query pulling all of the child pages. I’d like to know how I can make each of these child pages display according to their chosen page template.
Thanks.
2 Answers
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();
}