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

谁说胖子不能爱 提交于 2019-11-27 14:32:34
Drew Baker

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!