Using the get_posts() method, I get and display the last 5 posts. They are displayed as a slider. Each slide is a different color. Only 3 colors: yellow, green and blue. How can I add a class to each of the 5 slides to give a different background? The first 3 slides should be yellow, green and blue, and the rest should be yellow and green. How can i do this? Now I tried to implement this functionality, but the class on each slide is yellow-slide
My Code:
<?php
$last_posts = get_posts(array(
'numberposts' => 5,
'orderby' => 'date',
'post_type' => 'post',
));
global $post;
$bgcolor = '';
if ($counter == 0) {
$bgcolor = 'yellow-slide';
} else if ($counter == 1) {
$bgcolor = 'green-slide';
} else if ($counter == 2) {
$bgcolor = 'blue-slide';
} else if ($counter == 3) {
$bgcolor = 'yellow-slide';
} else {
$bgcolor = 'green-slide';
}
?>
<div class="swiper">
<div class="swiper-wrapper">
<?php $counter = 0;
foreach ($last_posts as $post) :
setup_postdata($post); ?>
<div class="swiper-slide <?php echo $bgcolor ?>"></div>
<?php $counter++ ?>
<?php endforeach;
wp_reset_postdata(); ?>
</div>
</div>
2
Answers
Your PHP code is executed in the order it’s written in, so your
if
-statements will be executed before you’ve even started theforeach
-loop (and before the variable$counter
even exist). It should actually throw a bunch of "Undefined variable: $counter"-warnings/notices.There is an easier way though.
Something like this:
Then after you’ve defined that array, you can do:
Please try this and check again.