Skip to content

Instantly share code, notes, and snippets.

@isotrope
Created April 1, 2020 13:51
Show Gist options
  • Save isotrope/b19e68cb329106c31fe5719003f243f1 to your computer and use it in GitHub Desktop.
Save isotrope/b19e68cb329106c31fe5719003f243f1 to your computer and use it in GitHub Desktop.
Get a random image or image src from Unsplash
<?php
/**
* Grab a placeholder image from Unsplash
* https://source.unsplash.com/
*
* @author Michal Bluma
*
* @param int $width Desired width
* @param int $height Desired height
* @param bool $src_only Url to the image only(true) or an image tag (false)
*
* @param bool $randomize_sizes Try to avoid repeating the same image by slightly varying the size, creating a
* different seed? Useful if using something like object-fit. Less so if you need extra
* an extra specific size
*
* @param int $random_deviation How much can the size vary? (only applicable if $randomize_sizes is true
*
* @return string
*
*
* Uses:
* iso_random_unsplash( 500, 500 );
* <img src="<?php echo iso_random_unsplash( 250, 300, true); ?>">
*
*/
function iso_get_random_unsplash( $width, $height, $src_only = false, $randomize_sizes = true, $random_deviation = 5 ) {
if ( $randomize_sizes ) {
$height = rand( ( $width - $random_deviation ), ( $width + $random_deviation ) );
$width = rand( ( $height - $random_deviation ), ( $height + $random_deviation ) );
}
$src = 'https://source.unsplash.com/random/' . $width . 'x' . $height;
if ( $src_only ) {
return esc_url( $src );
}
return '<img src="' . esc_url( $src ) . '" role="presentation" alt="">';
}
@ziad-saab
Copy link

iso_get_random_unsplash vs. iso_random_unsplash. Fix ittttt!!!

@isotrope
Copy link
Author

isotrope commented Apr 1, 2020

@ziad-saab It's the ole get_* vs the_* WordPress habits.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment