user1961395
user1961395

Reputation: 57

Wrap every x amount of items inside a div - Php while loop

I have some code that is working to wrap every 2 posts in a div. I am now wanting to wrap the posts in a div every 6 or maybe 8.

The code is here:

<?php 

            $loop = new WP_Query( array( 
                'post_type' => 'latest_posts', 
                'posts_per_page' => 100, 
                'post_status' => 'publish' ) ); ?>

                <?php $i = 0; ?>
                
            <?php while ( $loop->have_posts() ) : $loop->the_post(); ?>

                <?php if ( $i % 2 ==  0) : ?>
                    <div class="flex-content-container">
                <?php endif; ?>

                <div class="latest-posts">

                        <h3><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h3>
                
                </div>

                <!-- changed == 0 to != 0  -->
                <?php if ( $i % 2 != 0 ) : ?>
                    </div>
                <?php endif; ?>

            <?php $i++; endwhile; 
            ?>

            <?php wp_reset_query(); ?>

             <!-- added closing </div> for odd number of posts -->
        <?php if ( $i % 2 != 0 ) : ?>
        </div>
            </div>
        <?php endif; ?>

I thought I could just change the 2 to whatever number I wanted but that didn't seem to work.

Any help please?

Upvotes: 1

Views: 299

Answers (1)

Sagive
Sagive

Reputation: 1827

Here you go, i organized a bit - hope it's to your liking (each coder etc)
you can set the "divider" at the top.

<?php
$result     = '';
$posts      = array();
$divider    = 6;

// The Query
$args = array(
    'post_type'     => 'latest_posts', 
    'posts_per_page'=> 100, 
    'post_status'   => 'publish'
);
$query = new WP_Query( $args );

// The Loop
if ( $query->have_posts() ) {
    while ( $query->have_posts() ) {
    $query->the_post();
    
        $posts[] = '
        <div class="post">
            <div class="p-3">
                <a href="'.get_the_permalink().'">'.get_the_title().'</a>
            </div>
        </div>
        ';

    }
}
wp_reset_postdata();


$postsGrouped = array_chunk($posts, $divider);

foreach($postsGrouped as $group){
    $result .= '<div class="flex-container">'.implode('', $group).'</div>';
}
?>

<div class="latest-posts"><?php echo $result; ?></div>

Explanation:
We are running through posts, collecting them into an array and at the end we use 'array_chunk' function to group them. Then rebuild for echoing and were done.

Control the number of items per block / wrap here:

$divider    = 6;

Please note:
in this line, we are wrapping with a final div

echo '<div class="latest-posts">'.$result.'</div>';

You can control what class that div has.

Upvotes: 2

Related Questions