Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop through WordPress posts, and wrap each X post in a DIV [duplicate]

Note: This is a self Q&A

When building asymmetrical grid layouts in WordPress, it's common that you'd want to wrap each X post in a div, like so:

div
    post
    post
/div
div
    post
    post
/div
div
    post
    post
/div

I'd like to avoid using a modulo operator as it gets confusing quickly.

like image 239
Drew Baker Avatar asked Jan 09 '23 00:01

Drew Baker


1 Answers

Most people do this with a modulo operator, but it gets awkward to do it if no posts are found, or and even division occurs on the last post. I've expanded on the answer provided here by @The Shift Exchange to do it in a cleaner way.

<?php
    // Get posts (tweak args as needed)
    $args = array(
        'post_type'        => 'page',
        'orderby'          => 'menu_order',
        'posts_per_page'   => -1,
        'post_parent'      => $post->ID,
        'order'            => 'ASC'
    );
    $posts = get_posts( $args );
?>

<?php foreach (array_chunk($posts, 2, true) as $posts) :  ?>

    <div class="row">

        <?php foreach( $posts as $post ) : setup_postdata($post); ?>

            <a id="post-<?php the_ID(); ?>" <?php post_class(); ?> href="<?php the_permalink(); ?>">
                <?php the_post_thumbnail(); ?>
            </a>

        <?php endforeach; ?>

    </div>

<?php endforeach; ?>

You would change the "2" in the first foreach loop to be the amount you want grouped per row.

like image 148
Drew Baker Avatar answered Jan 19 '23 12:01

Drew Baker