PHP Wordpress 循环 2 个帖子回显类,第三个帖子回显 class2


PHP Wordpress loop for 2posts to echo class and third to echo class2

Problem.我试图做的是调用一个特定于类别的循环,但是,我希望从最近的第一个返回的内容显示,以数字编号,以便对于显示的每 2 个,将回显确定给他们的 css 类和第三个结果显示一个完全不同的类,因为这就是我编写 html 的方式。这是我试图让 HTML 显示的内容:

<div id="content">
    <div class="block1"></div>
    <div class="block1"></div>
    <div class="block2"></div>
    <div class="block1"></div>
    <div class="block1"></div>
    <div class="block2"></div>
</div>

如果有更多的结果,那么前两个将在第一个div 中命名,所有结果中的第三个将分配该类名。帮助将不胜感激。

说:

<?php query_posts( 'cat=featured&showposts=4' ); ?>
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<?php foreach($recent as $index => $postObj) {
  $class = $index + 1 % 3 === 0 ? 'block2' : 'block1'; 
}
?>
<h1><?php the_title(); ?></h1>
<?php endwhile; else: ?>
<p>Sorry, no posts matched your criteria.</p>
<?php endif; ?>
<?php get_footer(); ?>

但是它返回的帖子数量,但在帖子下返回 警告:为 foreach() 提供的参数无效尝试过反复试验,但是,我认为我的语法很糟糕。

你要找的是模运算符。模的作用是找到除法运算的其余部分。实际上,结果在 0..N-1 的范围内,其中 N % N = 0。

foreach($posts as $index => $postObj) {
  $class = $index + 1 % 3 === 0 ? 'block2' : 'block1';

这将完成您想要的,因为循环逻辑如下所示:

1 % 3 = 1 -> block1
2 % 3 = 2 -> block1
3 % 3 = 0 -> block2

您的代码需要:

<?php
  query_posts( 'cat=featured&showposts=4' );
  $index = 1;
  if ( have_posts() ) :
    while ( have_posts() ) : the_post();
    $class = $index++ % 3 === 0 ? 'block2' : 'block1'; 
?>
<div class="<?php echo $class ?>">
  <h1><?php the_title(); ?></h1>
</div>
<?php endwhile; else: ?>
<p>Sorry, no posts matched your criteria.</p>
<?php endif; ?>
<?php get_footer(); ?>

$index++运算符的意思是"在使用它后递增$index"。因此,请注意循环是如何设置的。在循环之前,我们将$index设置为 1。在循环中,我们使用我们的模技术设置$class,然后递增$index .然后我们必须创建一个容器 DIV,就像你提到的,并在那里回显类。