WordPress loop repeating within the foreach loop when listing child pages

I’ve created a loop which is getting the correct child pages and their content, however it’s staggering/repeating the page content on the foreach loop.

The boxes (in order) should appear with the following content:

Read More

Box 1: PRESS
Box 2: TV SHOWS
Box 3: Radio Shows
Box 4: Gallery

However as you can see it’s doing the following:

Box 1: Press
Box 2: Press, TV Shows
Box 3: Press, TV Shows, Radio Shows
Box 4: Press, TV Shows, Radio Shows, Gallery

<?php
    //get current page ID
    $the_id = get_the_ID();

    $args = array(
    'child_of'     => $the_id,
    'title_li'     => '',
    'parent'       => $the_id,
    'sort_order'    => 'DESC',
    'sort_column'   => 'menu_order'
    );

    $pages = get_pages( $args );

    $output = '';

    foreach($pages as $value){ ?>

    <div class="col-xs-12 col-sm-6">
        <div class="row">
            <div class="col-xs-12">
                <?php
                $thumb = get_the_post_thumbnail( $value->ID, $attr = ' img-responsive' );
                $output .= "<div class='thumbnailcontainer'><a href='" . $value->post_name . "' >" . $thumb  . "<span>" . $value->post_title . "</span></a></div>";

                echo $output;

                ?>
            </div>
        </div>
    </div>
    <?php } ?>

I tried limiting the posts_per_page to 1 but no difference.

enter image description here

Related posts

1 comment

  1. Replace the $output .= with $output = on line 24. 🙂 I think that should solve it.

    or what you could try is:

    <?php
        //get current page ID
        $the_id = get_the_ID();
    
        $args = array(
        'child_of'     => $the_id,
        'title_li'     => '',
        'parent'       => $the_id,
        'sort_order'    => 'DESC',
        'sort_column'   => 'menu_order'
        );
    
        $pages = get_pages( $args );
    
        $output = '';
    
        foreach($pages as $value) {
            $thumb = get_the_post_thumbnail( $value->ID, $attr = ' img-responsive' );
            $output .= "<div class='thumbnailcontainer'><a href='" . $value->post_name . "' >" . $thumb  . "<span>" . $value->post_title . "</span></a></div>";
        }
    ?>
    
        <div class="col-xs-12 col-sm-6">
            <div class="row">
                <div class="col-xs-12">
                    <?=$output?>
                </div>
            </div>
        </div>
    

    Btw, try to avoid mixing PHP and HTML as much as possible! 😉

Comments are closed.