Reputation: 1137
I'm using a php loop on my website. I'm trying to randomly add a class "current" to a div inside this loop. I know how to do it using jQuery but I'd liek to use php to achieve this. here is my loop :
<?php if (have_posts()) : ?>
<div id="random_backgrounds">
<?php while (have_posts()) : the_post(); ?>
<div id="background_directors" class="" background_ID="<?php the_ID();?>" style="background: url(<?php the_post_thumbnail_url( 'large' ); ?>) no-repeat center center fixed" ></div>
<?php endwhile; ?>
</div>
<?php endif; ?>
I'd like to add the "current" class randomly to the "background_directors" div.
can anybody help me with this ?
Upvotes: 1
Views: 1052
Reputation: 1278
You can try something like this :
<?php
if (have_posts()) :
$numberPost = count(have_posts());
$isAlreadyActive = false;
$i = 1;
echo '<div id="random_backgrounds">';
while (have_posts()) :
the_post();
$class = "";
if(!$isAlreadyActive && rand(0, 1) == 1 || !$isAlreadyActive && $i == $numberPost):
$class = "current";
$isAlreadyActive = true;
endif;
echo '<div id="background_directors" class="' . $class . '" background_ID="' . the_ID() . '" style="background: url(' . the_post_thumbnail_url( "large" ) . ') no-repeat center center fixed" ></div>';
$i++;
endwhile;
echo '</div>';
endif;
?>
Upvotes: 3
Reputation: 852
Somethink like this ?
$test = ['class1', 'class2', 'class3'];
<div id="background_directors" class="<?=$test[rand(0,2)]?>" background_ID="<?php the_ID();?>" style="background: url(<?php the_post_thumbnail_url( 'large' ); ?>) no-repeat center center fixed" ></div>
Upvotes: 1