ultraloveninja
ultraloveninja

Reputation: 2139

Use PHP to duplicate div and randomize

I'm using ACF with WordPress to loop through a set of images to display them:

<div class="logos">
  <?php if (have_rows('logos')) : while (have_rows('logos')): the_row();
      $image  = get_sub_field('logo');
      $link   = get_sub_field('logo_link');
      ?>
      <div class="img"><a target="_blank" href="<?php echo $link; ?>"><img src="<?php echo $image['url']; ?>" alt="<?php echo $image['alt']; ?>"></a></div>
    <?php endwhile; endif; ?>
</div>

What I'm wondering is if it's possible to duplicate the div of logos 4 more times and then randomize the return of the loop of the images? Not sure if that's possible with PHP or if jQuery might be the better way to go about it instead?

Upvotes: 0

Views: 552

Answers (1)

Sjors
Sjors

Reputation: 1215

Yes that is possible! Instead of using have_rows you can use get_field. The result is an array. You can then use php's rand function and foreach to loop over the array.

Check this ACF example enter link description here for batter understanding.

I didn't check the exact output of get_field in the example below, but you'll get the idea :)

<?php

$images = get_field( 'logos' );
$images1 = rand( $images );
$images2 = rand( $images );
$images3 = rand( $images );
$images4 = rand( $images );

?>

<div class="logos">
    <?php foreach ( $images1 as $image ) : ?>
        <div class="img"><a target="_blank" href="<?php echo $image['logo_link']; ?>"><img src="<?php echo $image['logo']['url']; ?>" alt="<?php echo $image['logo']['alt']; ?>"></a></div>
    <?php endforeach; ?>
</div>

<div class="logos">
    <?php foreach ( $images2 as $image ) : ?>
        <div class="img"><a target="_blank" href="<?php echo $image['logo_link']; ?>"><img src="<?php echo $image['logo']['url']; ?>" alt="<?php echo $image['logo']['alt']; ?>"></a></div>
    <?php endforeach; ?>
</div>

<div class="logos">
    <?php foreach ( $images3 as $image ) : ?>
        <div class="img"><a target="_blank" href="<?php echo $image['logo_link']; ?>"><img src="<?php echo $image['logo']['url']; ?>" alt="<?php echo $image['logo']['alt']; ?>"></a></div>
    <?php endforeach; ?>
</div>

<div class="logos">
    <?php foreach ( $images4 as $image ) : ?>
        <div class="img"><a target="_blank" href="<?php echo $image['logo_link']; ?>"><img src="<?php echo $image['logo']['url']; ?>" alt="<?php echo $image['logo']['alt']; ?>"></a></div>
    <?php endforeach; ?>
</div>

Or use a for loop:

<?php $images = get_field( 'logos' ); ?>

<?php for ( $i = 1; $i <= 4; $i++ ) : $randImages = rand( $images ); ?>
    <div class="logos">
        <?php foreach ( $randImages as $image ) : ?>
            <div class="img"><a target="_blank" href="<?php echo $image['logo_link']; ?>"><img src="<?php echo $image['logo']['url']; ?>" alt="<?php echo $image['logo']['alt']; ?>"></a></div>
        <?php endforeach; ?>
    </div>
<?php endfor; ?>

Upvotes: 2

Related Questions