4
votes

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(); ?>
2
Can't you put a width on the container these posts go into? Make it wide enough to fit 3 posts in, then when it gets to the 4th post there is no more room on that line so it will pop it underneath.Adam Tomat
I see what you mean. But the items might not in the same height, also with margins, paddings stuff. It's always good to have more css classes for better control.solidcolour

2 Answers

4
votes
<?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

2
votes
<?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 = '';
    }