Don't like ads? PRO users don't see any ads ;-)
Guest

Display a random image

By: a guest on Feb 14th, 2011  |  syntax: PHP  |  size: 1.11 KB  |  hits: 179  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
This paste has a previous version, view the difference. Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. <?php
  2. /* Display a random image
  3. Assumes 8 .jpg images in the images/random sub-folder numbered 1 to 8 (1.jpg, 2.jpg etc)
  4. Plus a fallback image called default.jpg.
  5. All images should have the same dimensions.
  6. */
  7. // define image width in pixels
  8. $random_img_width = 150;
  9.  
  10. // define image height in pixels
  11. $random_img_height = 150;
  12.  
  13. // define the first part of the image's url
  14. $random_img_src = get_stylesheet_directory_uri() . '/images/random/';
  15.  
  16. // Generate a random number from 1 to 8
  17. $random_img_num = rand(1, 8);
  18.  
  19. // Create a potential image url
  20. $random_img = $random_img_src . $random_img_num . '.jpg';
  21.  
  22. // Does the image actually exist? If, yes - display it
  23. if( file_exists(get_stylesheet_directory() . '/images/random/' . $img_num . '.jpg'))  echo '<img class="random-image" src="' . $random_img . '" width="<?php echo $random_img_width;?>" height="<?php echo $random_img_height;?>" alt="" />';
  24.  
  25. // If no, use the fallback default.jpg image
  26. else echo '<img class="random-image" src="' . $random_img . '" width="<?php echo $random_img_width;?>" height="<?php echo $random_img_height;?>" alt="" />';
  27. ?>