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

时光毁灭记忆、已成空白 提交于 2019-11-26 22:24:31

问题


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.



来源:https://stackoverflow.com/questions/28247770/loop-through-wordpress-posts-and-wrap-each-x-post-in-a-div

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