views:

60

answers:

2

I'm working on wordpress query_posts. I want to show 12 posts on the index page,3 items in a row. So I want to have a "clear:both" css on the first item of each row. How can I do that please?

<?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(); ?>
+1  A: 
<?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 3rd item class, I would suggest adding class to all items, for simplicity and even more control

To do so, before the loop:

$i = 0;

Inside the div in the loop:

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

So that, for each line, the first item has class = item-1, the 3rd item has class = item-3

PeterWong
Can we add another class "last_item" to the 3rd item of each row please? Thanks!
solidcolour
@solidcolour Please see my updated answer.
PeterWong
+1  A: 
<?php
    $counter = 0;
    if (have_posts() ....): the_post(); ?
        $class = ((++$counter % 3) == 0) ? ' class="clearme"': '';
?>
    <div<?php echo $class ?>> <!-- clear.... -->
         ...

Initialize your counter to be zero. Increment it by one, divide by 3 and check if the remainder is 0 (implying it's an even multiple of 3), in which case you set your clearing class/style. In less terse 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 = '';
    }
Marc B
thanks, that was very clear!
solidcolour