We launched new forums in March 2019—join us there. In a hurry for help with your website? Get Help Now!
    • 15469
    • 64 Posts
    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.
      $cd /pub
      $more beer
      • 3534
      • 6 Posts
      On my site it keeps choosing one particular img out of three (random_01.jpg). Can you please explain those two TVs a little more? What widget type they should be?

      Edit: My fault! It was cacheing ;/