I'm changing the default layout for gallery shortcode. I have this in my functions.php:

$attr['columns'] = 1;
$attr['size'] = 'full';
$attr['link'] = 'none';

$attr['orderby'] = 'post__in';
$attr['include'] = $attr['ids'];

These are hardcoded default options, which allow me to set max-width to all images whithin the .gallery:

$.each($('.gallery img'), function () {
        'max-width' : 300

After that I'm running masonry and it looks almost perfect. My problem is... that I want to set random max-width in one of the following ways:

1) randomly set max-width to each image from an array with three or four values

2) generate random even number withing a range (say 260 to 480 with a 20px "step") and set it as max-width

...and I have no clue how to achieve that. It's been dozens of google search queries and still I'm floating in nowhere. I've tried simple javascript math.floor and math.random function, but I'm not a programmer, I guess I'm doing something wrong. I want to make galleries mobile-friendly.

Will appreciate your help.

1 Answer 1


try it like this:

$.each($('.gallery img'), function () {
  var rndmnum = Math.floor((Math.random()*11)+1);
  rndmnum = rndmnum *20 + 260;

     'max-width' : rndmnum

note: untested


edit: corrected calculation


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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