WordPress: Include page template dynamically foreach $pages

I’m working on a one-page-wp-site, using each page created as a new slide/section of the content. I wanted different templates for different slides, and had a problem including each template dynamically, but finally figured it out how to do it.

original php:

<?php 
    $pages = get_pages(array('sort_column' => 'menu_order'));
    foreach ($pages as $page_data) {
        $page_ID = $page_data->ID;
        $template = get_current_template();

?>  
<section id="<?php echo $slug ?>" class="slide cf">                     
        <?php include($template) ?>

</section>  
<?php 
    } /*end foreach*/
?>

Related posts

2 comments

  1. Using include or require_once inside of a template is not the WordPress Way. (For more on why, see this article) WordPress has exposed specific functions for this for a reason – use get_template_part

    Note that with this function, templates can be located where they should be – in the theme folder. With include, you’re not going to load them from the proper location (include will load from the root folder, where index.php is located, unless the $template variable has the full path, which would get messy and be hard to maintain).

    <?php 
        $pages = get_pages( array( 'sort_column' => 'menu_order' ) );
        foreach ($pages as $page_data) {
            $page_ID = $page_data->ID;
            $template = get_page_template_slug( $page_ID );
    ?>  
            <section id="<?php echo $slug; ?>" class="slide cf">                     
                <?php get_template_part($template); ?>
            </section>  
    <?php } ?>
    
  2. New php:

    <?php 
        $pages = get_pages(array('sort_column' => 'menu_order'));
        foreach ($pages as $page_data) {
            $page_ID = $page_data->ID;
            $template = get_page_template_slug( $page_ID );
    
    ?>  
    <section id="<?php echo $slug ?>" class="slide cf">                     
            <?php include($template) ?>
    
    </section>  
    <?php 
        } /*end foreach*/
    ?>
    

Comments are closed.