簡體   English   中英

簡單的PHP計數器

[英]simple php counter

我正在研究wordpress query_posts。 我想在索引頁面上顯示12個帖子,連續3個項目。 所以我想在每行的第一項上有一個“清楚:兩個”的CSS。 我該怎么辦?

<?php query_posts(array('showposts' => 9, 'post_parent' => $post->ID, 'post_type' => 'page', 'order' => 'ASC')); ?>
<div>
    <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
        <div> <!-- clear class on each 4th item -->
            <h2><?php the_title(); ?></h2>
            <?php the_content(); ?>
        </div>
    <?php endif; ?>
</div>
<?php wp_reset_query(); ?>
<?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行。

<?php $i = 0; $attr = " class='clear_float'"; ?>

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

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

要添加第3個項目類,我建議為所有項目添加類,以簡化和更多控制

為此,在循環之前:

$i = 0;

在循環中的div內:

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

因此,對於每一行,第一項具有class = item-1 ,第三項具有class = item-3

<?php
    $counter = 0;
    if (have_posts() ....): the_post(); ?
        $class = ((++$counter % 3) == 0) ? ' class="clearme"': '';
?>
    <div<?php echo $class ?>> <!-- clear.... -->
         ...

將計數器初始化為零。 將其遞增1,除以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 = '';
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM