TechyDude
TechyDude

Reputation: 1165

Wordpress: Query child pages with specific templates for each page

I created a query to call all child pages of the current parent page. This works great, however each child page has a custom template. I don't know how to add a custom query parameter to account for the template. Currently I query the_content for each child page, however that doesn't account for the template.

Can anyone help me modify the query?

<?php $children = get_pages( 
    array(
        'sort_column' => 'menu_order',
        'sort_order' => 'ASC',
        'hierarchical' => 0,
        'parent' => $post->ID,
        'post_type' => 'projects',
        'meta_query' => array(
            array(
                'key' => '_wp_page_template',
                'value' => 'template-city.php', // template name as stored in the dB
            )
        )
    ));

foreach( $children as $post ) { 
        setup_postdata( $post ); ?>
    <div class="section-container">
        <?php the_content(); ?>
    </div>
<?php } ?>

Upvotes: 0

Views: 1473

Answers (2)

skiplecariboo
skiplecariboo

Reputation: 852

You can use get_post_meta !

With template_redirect action :

function my_page_template_redirect()
{
    global $post;
    if(get_post_type($post) == 'projects' )
    {
         $tpl = get_post_meta($post->ID, '_wp_page_template');
         if ($tpl) {
             include( get_template_directory() . $tpl );
             exit();
         }
    }
}    
add_action( 'template_redirect', 'my_page_template_redirect' );

Upvotes: 1

Igor Jerosimić
Igor Jerosimić

Reputation: 13741

I think get_pages function doesn't use meta_query, you need to do something like this:

$children = get_pages( 
    array(
        'sort_column' => 'menu_order',
        'sort_order' => 'ASC',
        'hierarchical' => 0,
        'parent' => $post->ID,
        'post_type' => 'projects',
        'meta_key' => '_wp_page_template',
        'meta_value' => 'template-city.php',
    ));

Or use get_posts function that uses meta_query.

Upvotes: 1

Related Questions