Last active
December 1, 2018 15:30
-
-
Save lawebfabric/c48a7f47e82a269023aa3d6a77b776b2 to your computer and use it in GitHub Desktop.
This snippet will return chunks in a random order.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
//----------------------------------------------------------- | |
// randomChunk | |
//----------------------------------------------------------- | |
/* | |
* @author: Steeve from lawebfabric | |
* @website: http://www.lawebfabric.com | |
* @tutorial modx website: http://www.tutocms.fr/ | |
* | |
* Created on: 08/10/18 | |
* | |
* DESCRIPTION | |
* This snippet will return chunks in a random order. | |
* | |
* PROPERTIES: | |
* &chunks string of all name chunks comma separated. Required! | |
* &howManyChunks integer. If not define all chunks will be displayed. | |
* | |
* USAGE: | |
* [[!randomChunk? &chunks=`firstChunkName,secondChunkName,nameofchunk,anotherChunk` &howManyChunks=`2`]] | |
* | |
*/ | |
$chunks = $modx->getOption('chunks', $scriptProperties); | |
$howManyChunks = $modx->getOption('howManyChunks', $scriptProperties); | |
$output = false; | |
$chunksArray = explode(",", $chunks); | |
$totalChunks = count($chunksArray); | |
// ERRORS | |
if (!isset($scriptProperties['chunks'])) { | |
$modx->log(modX::LOG_LEVEL_ERROR, '[randomChunk] missing required properties &chunks!'); | |
return; | |
} | |
if (isset($scriptProperties['howManyChunks']) && $howManyChunks > $totalChunks) { | |
$modx->log(modX::LOG_LEVEL_ERROR, '[randomChunk] howManyChunks properties is bigger than the number of chunks'); | |
return; | |
} | |
// rand the array (keep assoc key => value) | |
function arrayKeyShuffle(&$array) { | |
if(!is_array($array) || empty($array)) { | |
return false; | |
} | |
$tmp = array(); | |
foreach($array as $key => $value) { | |
$tmp[] = array('k' => $key, 'v' => $value); | |
} | |
shuffle($tmp); | |
$array = array(); | |
foreach($tmp as $entry) { | |
$array[$entry['k']] = $entry['v']; | |
} | |
return true; | |
} | |
// shuffle chuks array | |
arrayKeyShuffle($chunksArray); | |
if(isset($scriptProperties['howManyChunks'])) { | |
$i=0; | |
$rand_keys = array_rand($chunksArray, $howManyChunks); | |
// retunr number of chunks asked in howManyChunks properties in a random order | |
while ($i < $howManyChunks) { | |
$output .= $modx->getChunk($chunksArray[$rand_keys[$i]],array()); | |
$i++; | |
} | |
}else{ | |
// return random all chunks | |
foreach ($chunksArray as $chunk) { | |
$output .= $modx->getChunk($chunk,array()); | |
} | |
} | |
return $output; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment