我用这个把头发拉出来!以下代码每2个帖子正确插入一个div作为类。 HOwever,当有偶数帖子时,它会在下面显示一个额外的空div。有人可以帮忙吗?
谢谢!
<div class="row">
<?php
$connected = new WP_Query( array(
'connected_type' => '2-col-module_to_pages',
'connected_items' => get_queried_object(),
'nopaging' => true,
) );
if ($connected->have_posts() ) : while ($connected->have_posts()) : $connected->the_post(); ?>
<div class="tile">
<div class="wrapper">
<div class="content">
<h2><?php the_title();?></h2>
</div>
</div>
</div>
<?php $counter++;
if ($counter % 2 == 0 ) {
echo '</div><div class="row">';
}
endwhile; wp_reset_postdata(); endif; ?>
</div>
答案 0 :(得分:0)
当你拿到最后一篇文章时,你将不再拥有;所以你可以在回应空div之前再次询问:
$counter++;
if ($counter % 2 == 0 )
{
if ( more_posts() )
{
echo '<div class="row"></div>'; // It was </div><div class="row"> which always left an open div
}
}
您可以将more_posts()
功能添加到WordPress'functions.php
文件中。
function more_posts()
{
global $wp_query;
return $wp_query->current_post + 1 < $wp_query->post_count;
}
注意:此解决方案来自WordPress的Codex:http://codex.wordpress.org/Function_Reference/have_posts