2

I am developing a generic widget that randomly selects an image to be displayed. I only have 5 images to choose from. Is there any way to limit the number of widgets to 5, so that there are no repeat images/widgets?

  • If you have 2 ( of the same ) widgets both randomly selecting images to display there will still be a chance that they both display the same image. You could try is_active_widget() but as I've never used it I'm not sure if that's what you're looking for ( though it does sound like ti should work ). – Howdy_McGee Jan 15 '15 at 20:17
1

Widget are PHP classes, so you can use static class variables to count how many times a widget is used.

As @Howdy_McGee noted, if your widget show images randomly there are chances that there are widget showing same image even if there are same number of widgets and images, so you need also to address that issue.

This is a rough, untested example that may put you on the way to solve your issue:

class MyRandomImgWidget
{
  private static $inited;
  private static $images;

  function __construct()
  {
    parent::__construct('my-random-img', __('My Random Image', 'text_domain'));
  }

  function init() {
    // get_images_url() below is a placeholder function to be replaced to actual code
    // that retrieve/set images urls.
    self::$images = get_images_url();
    self::$inited = true; // make this method run only once
  }

  function widget() {
    if (is_null(self::$inited)) { // only on first run
      $this->init();
    } elseif(empty(self::$images)) { // do nothing if no images
      return;
    }
    $key = array_rand(self::$images); // get a random key from images array
    $image = self::$images[$key];  // get related image url 
    // remove image from array, so in next call will not used again
    unset(self::$images[$key]);
    printf('<img src="%s" alt="" />', $image); // print the image
  }
} 

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.