Special Random Collection

I created this custom pages method to create chunks of random size. Save it in a plugin file, e.g. site/plugins/methods.php.

  /**
   * Creates chunks of random size
   *
   * @param int $min Minimum number of items in chunk
   * @param int $max Maximum number of items in chunk
   * @return object A new collection with an item for each chunk and a subcollection in each chunk
   * Usage:
   * $projects = page('projects')->children()->shuffle();
   * $max = mt_rand(1,$projects->count());
   * $min = mt_rand(1, $max);
   * $chunks = $projects->randomChunk($min,$max);
   */
pages::$methods['randomChunk'] = function($pages, $min, $max) {
  $temp = clone $pages;
  $chunks = [];
  $size=1;
  ($min >=1 && $min <= $max)? $min=$min:$min=1;
  $max = $max <= $pages->count()? $max: $pages->count();
  while ($temp->count() > 0) {
    $size = mt_rand($min,$max);
    array_push($chunks, array_splice($temp->data,0, $size));
  }
  $chunkCollections = [];
  foreach($chunks as $items) {
    $collection = clone $pages;
    $collection->data = $items;
    $chunkCollections[] = $collection;
  }
  // convert the array of chunks to a collection object
  return new Collection($chunkCollections);
};

Use in your template

<?php
$projects = page('projects')->children()->visible()->shuffle();

/**
 **create random $min and $max values;
 ** these set the range for the random $size variable within the randomChunk() method; 
 ** instead of random values, you can also set one or both parameters to a fixed value, 
 ** depending on what sorts of results you want to get
*/
$max = mt_rand(1,$projects->count());
$min = mt_rand(1, $max);

$chunks = $projects->randomChunk($min,$max);
// $chunks is a nested collection, so we need two foreach loops to get the chunks and then all items in each chunk

foreach($chunks as $items): ?>
  <section>
    <?php foreach($items as $project): ?>
    <article class="">
      <?= $project->title()?>
    </article>
    <?php endforeach ?>
  </section>
  <hr>
<?php endforeach ?>
1 Like