我需要 PHP 代码在 WordPress 循环中的 DIV 内添加每 2 个项目。
例如,我需要这样:
<div class="wrap">
post
post
</div>
<div class="wrap">
post
post
</div>
<div class="wrap">
post
post
</div>
这是我的 WordPress 循环,但不起作用,我需要 DIV 中的每 2 个帖子:
<?php if ( have_posts() ) : // If have post start. ?>
<?php $i = 0; ?>
<?php while ( have_posts() ) : the_post(); // Start Loop: ?>
<?php if ( $i % 2 == 0) : ?>
<div class="wrap">
<?php endif; ?>
<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<?php the_content(); ?>
</article>
<?php if ( $i % 2 == 0 ) : ?>
</div>
<?php endif; ?>
<?php $i++; endwhile; // End Loop. ?>
<?php endif; // If have post end. ?>
谢谢。
最佳答案
问题是您同时打印了 <div>
和</div>
偶数 $i
。这就是为什么他们总是只包装一篇文章,而第二篇文章则放在一边。
您必须回显 <div>
偶数和 </div>
奇数:
<?php if ( have_posts() ) : // If have post start. ?>
<?php $i = 0; ?>
<?php while ( have_posts() ) : the_post(); // Start Loop: ?>
<?php if ( $i % 2 == 0) : ?>
<div class="wrap">
<?php endif; ?>
<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<?php the_content(); ?>
</article>
<!-- changed == 0 to != 0 -->
<?php if ( $i % 2 != 0 ) : ?>
</div>
<?php endif; ?>
<?php $i++; endwhile; // End Loop. ?>
<!-- added closing </div> for odd number of posts -->
<?php if ( $i % 2 != 0 ) : ?>
</div>
<?php endif; ?>
<?php endif; // If have post end. ?>
我添加了第二个 </div>
在循环之后,因为如果没有它,如果您有奇数个帖子,您根本不会获得结束标记。
关于PHP 在 WordPress 循环中的 DIV 内添加每 2 个项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36330700/