For whom it may concern...
I just created a neat little snippet that chooses an image randomly if not set explicitly via template variable.
(I use it for an images that are to be displayed in my site-header)
Code as follows:
<?php
define(IMAGE_DIR, "assets/images/");
define(ALT_TEXT, "alt-text here");
//fetch the template variable
$tv = $modx->getTemplateVar('random_images', "", $modx->documentIdentifier);
$randomizer = $tv['value'];
if($randomizer == -1)
{
$tv = $modx->getTemplateVar('keyvisual', "", $modx->documentIdentifier);
return "<img src='".$tv['value']."' alt='".ALT_TEXT."' />";
}
else
{
return selectRandomImage();
}
function selectRandomImage()
{
$files = scandir(IMAGE_DIR);
$count_files = (count($files)-1);
$random = rand(0,$count_files);
if($files[$random][0] != ".")
{
return "<img src='".IMAGE_DIR.$files[$random]."' alt='".ALT_TEXT."' />";
}
else
return selectRandomImage();
}
?>
Two TVs are needed to let this one run it´s way... [*random_images*] (values 1 or -1) and [*keyvisual*] (img-tag) to set an image explicitly when you don´t want a randomly chosen image.
Usage: [[name_of_snippet]] (prints an img-tag)
Any comments welcome!
Cheers.