[WordPress] Alternate a given parameter inside a looped element depending on even/odd iteration. Example: Alignment of a featured image inside a post query element.
<?php
/**
* Alternate a given parameter depending on a looped element counts even or odd.
*
* This would e.g. go somewhere inside the WordPress Loop.
*
* 1. Set up counting.
* 2. Determine whether current iteration counts odd or even.
* 3. Set a default value for parameter to be alternated.
* 4. Set up alternation.
* 5. Conditionally set alternated value for parameter depending on odd/even status of iteration.
*/
while ( have_posts() ) :
the_post();
// Count.
$i = ! isset( $i ) ? 1 : $i;
// Does this post count odd?
$maybe_odd = $i % 2; // 1/0
// Default parameter value.
$param = 'right';
// Alternated parameter value.
$param_alt = 'right' === $param ? 'left' : 'right';
// Does this post count even? If so, alternate param.
if ( ! $maybe_odd ) {
$param = $param_alt;
}
// Example: class attribute for post wrapper;
// alignright on odd, alignleft on even iteration.
$class = "align$param";
?>
<article class="post">
<figure class="featured-image <?php echo $class; ?>">
<img src="http://dummyimage.com/200x200/000/fff&text=<?php echo $class; ?>" />
<figcaption>This figure has a class of <code><?php echo $class; ?></code>.</figcaption>
</figure>
</article>
<?php
// Count up.
$i++;
endwhile;