【问题标题】:simple php counter简单的php计数器
【发布时间】:2011-04-15 07:16:36
【问题描述】:

我正在处理 wordpress query_posts。我想在索引页面上显示 12 个帖子,连续显示 3 个项目。所以我想在每行的第一项上都有一个“clear:both”css。请问我该怎么做?

9, 'post_parent' => $post->ID, 'post_type' => 'page', 'order' => 'ASC')); ?>

【问题讨论】:

  • 你不能在这些帖子进入的容器上设置一个宽度吗?让它足够宽以容纳 3 个帖子,然后当它到达第 4 个帖子时,那条线上没有更多空间,所以它会弹出它。
  • 我明白你的意思。但是这些项目可能不在同一高度,还有边距、填充物。拥有更多的 CSS 类以获得更好的控制总是好的。

标签: php wordpress counter


【解决方案1】:
<?php query_posts(array('showposts' => 9, 'post_parent' => $post->ID, 'post_type' => 'page', 'order' => 'ASC')); ?>
<div>
    <?php $i = 0; $attr = " class='clear_float'"; ?>
    <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
        <div<?php if(($i++)%3 == 0) {echo $attr;} ?>> <!-- clear class on each 4th item -->
            <h2><?php the_title(); ?></h2>
            <?php the_content(); ?>
        </div>
    <?php endif; ?>
</div>
<?php wp_reset_query(); ?>

我添加了 2 行。

&lt;?php $i = 0; $attr = " class='clear_float'"; ?&gt;

&lt;div&lt;?php if(($i++)%3 == 0) {echo $attr;} ?&gt;&gt; &lt;!-- clear class on each 4th item --&gt;

===== 更新 =====

要添加第 3 个项目类,我建议为所有项目添加类,以简化和更多控制

为此,在循环之前:

$i = 0;

在循环中的div 内:

<div class="item-<?php echo (($i++) % 3) + 1 ?>">

因此,对于每一行,第一项具有 class= item-1,第三项具有 class= item-3

【讨论】:

  • 我们可以在每行的第 3 项添加另一个类“last_item”吗?谢谢!
【解决方案2】:
<?php
    $counter = 0;
    if (have_posts() ....): the_post(); ?
        $class = ((++$counter % 3) == 0) ? ' class="clearme"': '';
?>
    <div<?php echo $class ?>> <!-- clear.... -->
         ...

将您的计数器初始化为零。将其加一,除以 3 并检查余数是否为 0(意味着它是 3 的偶数倍),在这种情况下,您可以设置清算类别/样式。更简洁的代码:

    $counter = $counter + 1;
    if ($counter > 3) {
        $counter = 0;
    }

    $remainder = (int)($counter / 3)
    if ($remainder == 1) {
         // will be 1 when $counter is 3
         $class = ' class="clearme"';
    } else {
         $class = '';
    }

【讨论】:

    猜你喜欢
    • 2014-06-12
    • 2014-02-22
    • 2011-11-20
    • 1970-01-01
    • 2017-09-23
    • 2011-07-31
    • 2015-01-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多