-1

On my homepage, I have 6 blocks including some custom fields each.

I would like to have a random display of these 6 blocks.

My codes simply looks like this :

<div class="bloc">
<h2><?php the_field('titre1'); ?></h2>
<div class="content">
<p><?php the_field('description1'); ?></p>
</div>
<p class="more"><a href="<?php the_field('url1'); ?>">read more</a></p>
</div>

<div class="bloc">
<h2><?php the_field('titre2'); ?></h2>
<div class="content">
<p><?php the_field('description2'); ?></p>
</div>
<p class="more"><a href="<?php the_field('url2'); ?>">read more</a></p>
</div>

<div class="bloc">
<h2><?php the_field('titre3'); ?></h2>
<div class="content">
<p><?php the_field('description3'); ?></p>
</div>
<p class="more"><a href="<?php the_field('url3'); ?>">read more</a></p>
</div>

etc... (6 times)

Do you know if there is a way to randomize this ?

I thank you in advance for your help !

Renato Gama
  • 16,431
  • 12
  • 58
  • 92
imudo
  • 91
  • 6
  • Do you mean you want 1 out of the 6 to show up (picked randomly) or are you wanting them ordered randomly but showing all 6 every time? – Nick M Nov 18 '13 at 21:45
  • 2nd option : I want them ordered randomly, showing 6 every times, yes – imudo Nov 18 '13 at 22:23

1 Answers1

0

Get each block and push it into a php array as a string. Then call shuffle($array) and then foreach through them to output them.

If you need more specific instructions, let me know. EDIT: Full instructions;

<?php 
// init array
$blocks = array();
// loop through 1 to 6
for($i=1;$i<=6;$i++) {
    // create a block of html
    // note I use $i here to get the correct fields
    // also note I've used get_field so its not echoed (as opposed to the_field)
    $block =    '<div class="bloc">
                    <h2>'.get_field('titre'.$i, 'option').'</h2>
                    <div class="content">
                        <p>'.get_field('description'.$i, 'option').'</p>
                    </div>
                    <p class="more"><a href="'.get_field('url'.$i, 'option').'">read more</a></p>
                </div>';
    // push this block of html into the array
    array_push($blocks, $block);
}
// shuffle the array of blocks randomly
shuffle($blocks);

// loop through them and echo out each html block
foreach ($blocks as $index => $block) {
    echo $block
} ?>

Good luck!

EDIT: Sorry, typed this out really quick and made a few errors.

Nick M
  • 1,647
  • 13
  • 17