Simple php counter

I am working on wordpress query_posts. I want to show 12 posts on an index page, 3 items per line. So I want to have "clear: both" css in the first element of each line. How can i do this?

<? 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 (); ?>
+3
source share
2 answers
<?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(); ?>

I added 2 lines.

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

and

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

===== UPDATED =====

To add a 3rd class class, I would suggest adding a class to all elements, for simplicity and even more control

To do this, before the loop:

$i = 0;

Inside divin a loop:

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

So, for each row, the first element has a class = item-1, the third element has a class =item-3

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

Initialize your counter to zero. Increase it by one, divide by 3 and check if the remainder is 0 (assuming it is even a multiple of 3), in which case you set your cleanup class / style. In less complex code:

    $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 = '';
    }
+2
source

Source: https://habr.com/ru/post/1765844/


All Articles