10

I have a Wordpress loop as follows:

<?php $loop = new WP_Query( array( 'post_type' => 'portfolio' ) ); ?>
    <?php while ( $loop->have_posts() ) : $loop->the_post(); ?>
    <div class="four columns">
        <?php the_content(); //along with other stuff in looped div ?>
    </div>
<?php endwhile ?>

How can I add an 'alpha' class to every (4n-3)th div (div.four.columns) and an 'omega' class to every (4n)th item using php?

Thanks (a lot!), Jamie

1
  • 7
    Keep a counter, starting from 0, and incremented by 1 each loop. Then if counter % 3 == 0 then it is "every 3rd loop". Likewise, counter % 4 == 0 for "every 4th loop". Do extra math as required. Commented Oct 2, 2012 at 20:53

2 Answers 2

29

Why not add a counter and use the modulus approach to get to know in every column what element you are currently echoing.

Lets say you have 4 columns as specified.
You start with counter = 1
1 % 4 = 1 ( you are in the first element )
2 % 4 = 2 ( you are in the second element )
3 % 4 = 3 ( you are in the third element )
4 % 4 = 0 ( you are in the fourth element )
5 % 4 = 1 ( you are in the first element )
6 % 4 = 2 ( you are in the second element )

And you just use an If statement with the class as following

<?php $counter = 1 ?>
<?php $loop = new WP_Query( array( 'post_type' => 'portfolio' ) ); ?>
    <?php while ( $loop->have_posts() ) : $loop->the_post(); ?>
    <div class="four columns <?php if ($counter % 4 == 1){echo 'alpha'}else if ($counter % 4 == 0){echo 'omega'} ?>">
        <?php the_content(); //along with other stuff in looped div ?>
    </div>
<?php $counter++ ; 
endwhile ?>
Sign up to request clarification or add additional context in comments.

Comments

2

Implementation from the comments made:

<?php $loop = new WP_Query( array( 'post_type' => 'portfolio' ) ); ?>
    <?php
        $i = 0;
        while ( $loop->have_posts() ) : $loop->the_post(); 
           if( $i % 4 == 0 )
             $class = 'omega';
           else
             $class = ''; 
        ?>
    <div class="four columns <?php echo $class ?>">
        <?php 
           the_content(); // Along with other stuff in looped div
           $i++;
        ?>
    </div>
<?php endwhile ?>

1 Comment

But you're not resetting $class on each loop. Once $class = 'omega'; does occur, $class will always be omega. $class = ''; should be inside of the while loop.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.