所以我已经为此寻找了一段时间的解决方案,但没有成功。有很多关于为偶数帖子和奇数帖子创建不同输出的信息,但我需要一些不同的东西。
基本上,我已经动态加载了添加到页面中的帖子。它们都是具有float: left
CSS规则的容器的50%。因此,如果帖子总数是偶数,那么看起来很棒,如果是奇数,那么在加载到页面的最后一篇帖子之后会有一个尴尬的空格。
我想创建一个规则,规定如果帖子总数是偶数,则应用此标记,如果是奇数,则应用备用标记。然后我可以取标记的最后一个子项,强制宽度从50%变为100%。
这是我的循环:
<?php $the_query = new WP_Query();
$x = 0;
while ( $the_query->have_posts() ) :
$the_query->the_post(); ?>
<article>
Some Content
</article>
<?php endwhile;
$x++;
wp_reset_query(); ?>
CSS:
article { width: 50%; float: left; }
我想要的是:
<?php if ($post_count = even) : ?>
<article>
Some Content
</article>
<?php elseif ($post_count = odd) : ?>
<article class="alt">
Some Content
</article>
<?php endif; ?>
CSS:
article { width: 50%; float: left; }
article.alt:last-child { width: 100%; }
有人熟悉如何做到这一点吗?一如既往,我们非常感谢您的帮助!
欢呼,
这里可以使用模数(%)运算符
if (($x % 2) == 1)
{
echo "odd";
}
if (($x % 2) == 0)
{
echo "even";
}
请参阅:php测试数字是否为奇数或偶数
你可以试试这个:
$count_posts = wp_count_posts();
$published_posts = $count_posts->publish;
if($published_posts % 2 == 0)
{
// even
}
else
{
//odd
}
如果你想知道各自的帖子是偶数还是奇数。。。请参阅以下内容:
<?php $postnum = 0;?>
if (have_posts()) : while (have_posts()) : the_post(); ?>
<?php $postnum++;
$alt = ( $postnum % 2 ) ? ' even_post' : ' odd_post';
?>