循环浏览WordPress帖子,并将每个X帖子包装在DIV中

问题描述:

注意:这是一个自我问答(Q& A)

在WordPress中构建非对称网格布局时,通常要将每个X帖子包装在div中,就像这样:

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.

大多数人使用模运算符来执行此操作,但是如果找不到任何帖子,或者甚至在最后一个帖子上进行除法,这样做都会很尴尬.我已经扩展了此处提供的答案通过@Shift Exchange以更清洁的方式进行操作.

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; ?>

您将在第一个foreach循环中将"2"更改为您希望每行分组的数量.

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