循环浏览 WordPress 帖子,并将每个 X 帖子包装在一个 DIV 中 [英] Loop through WordPress posts, and wrap each X post in a DIV

查看:26
本文介绍了循环浏览 WordPress 帖子,并将每个 X 帖子包装在一个 DIV 中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

注意:这是一个自我问答

在 WordPress 中构建非对称网格布局时,您通常希望将每个 X 帖子包装在一个 div 中,如下所示:

div邮政邮政/divdiv邮政邮政/divdiv邮政邮政/div

我想避免使用模运算符,因为它很快就会让人感到困惑.

解决方案

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

'页','orderby' =>'menu_order','posts_per_page' =>-1,'post_parent' =>$post->ID,'订单' =>'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;?>

<?php endforeach;?>

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

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.

解决方案

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.

这篇关于循环浏览 WordPress 帖子,并将每个 X 帖子包装在一个 DIV 中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆