【问题标题】:PHP Wordpress loop for 2posts to echo class and third to echo class2PHP Wordpress 循环 2 个帖子回显类和第三个回显类 2
【发布时间】:2012-06-29 03:45:13
【问题描述】:

问题。 我想要做的是调用一个特定于类别的循环,但是,我希望返回的内容从最近的第一个显示,以数字编号,以便对于显示的每 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() 提供的参数无效 然而,尝试过反复试验,我认为我的语法很糟糕。

【问题讨论】:

    标签: php html wordpress loops if-statement


    【解决方案1】:

    您正在寻找的是modulo operator。取模的作用是求除法运算的余数。实际上,结果在 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,就像你提到的那样,并在那里回显类。

    【讨论】:

    • 为食谱干杯,我已经添加了我试图解析的完整代码,你知道为什么它返回无效吗?
    • 谢谢。这很有帮助。我需要加强语法。慢慢来。 J
    猜你喜欢
    • 2016-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多