简体   繁体   中英

randomly add a class inside a php loop

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 ?

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; 
?>

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM