我需要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. ?>
谢谢。
问题是在$i
的偶数值上同时打印<div>
和</div>
。这就是为什么他们总是只包一根柱子,而第二根柱子站在一边。
你必须在偶数上回声<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>
,因为如果没有它,如果你有奇数个帖子,你就根本不会得到结束标记。
我认为这应该完成任务:
<div class="wrap">
<?php
$query = new WP_Query();
if ( $query->have_posts() ):
$i=0;
while ( $query->have_posts() ) :
$query->the_post();
if($i%2==0 && $i<$query->post_count-1 && $i>0):
echo '</div><div class="wrap">'
endif;
?>
<!--html here-->
<?php
$i++;
endwhile;
endif;
?>
</div>
您应该这样做:
<?php
if ( have_posts() ) {
$i=0;
while ( have_posts() ) {
if($i%2==0):?>
<div class="wrap">
<?php
else : ?>
</div>
<?php
endif;
$i++;
}
}
?>
好的,根据Aviram的回答,我创建了这个:
$i = 1;
$out = '';
$endingNeeded = false;
if ( have_posts() ) {
while ( have_posts() ) {
if ( $i % 2 == 1) {
$out .= '<div class="wrap">';
$endingNeeded = true;
}
the_post(); // Start Loop:
$out .= '<article id="post-'. get_the_ID().'" class="'.implode(get_post_class(), ', ').'">
'.get_the_content().'
</article>';
if ( $i % 2 == 0 ) {
$out .= '</div>';
$endingNeeded = false;
}
$i++;
}
}
if($endingNeeded) {
$out .= '</div>';
}
echo $out;
应该工作得很好。
正确的循环应该是这样的:
<?php if(have_posts()) : ?>
<?php $no_of_posts = wp_count_posts()->publish; ?>
<div class="wrap">
<?php $i=1; while(have_posts()) : the_post(); ?>
<div class="post">
post text
</div>
<?php if($i%2==0 && $i!=$no_of_posts) : ?>
</div>
<div class="wrap">
<?php endif; ?>
<?php $i++; endwhile; ?>
</div>
<?php endif; ?>
你的意思是这样的吗?
<?php
if ( have_posts() ) {
while ( have_posts() ) {
for ($i=0; $i<2; $i++) {
// what do you like to do
?>
<!-- HTML CODE -->
<?php
}
}
}else{
// ...
}
?>
为什么不在WordPress循环中添加一个简单的for循环?