Loop through WordPress posts, and wrap each X post

2019-01-11 21:12发布

问题:

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.

回答1:

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.