1

When using custom image sizes like:

function customImageSetup () {
  add_theme_support( 'post-thumbnails' );
  add_image_size('grid_1 mini square', 60, 60, TRUE);
  add_image_size('grid_2', 160);
  add_image_size('grid_2 square', 160, 160, TRUE);
  add_image_size('grid_4', 360);
  add_image_size('grid_4 square', 360, 360, TRUE);
  add_image_size('grid_6', 560);
  add_image_size('grid_6 square', 560, 560, TRUE);
  add_image_size('grid_8', 760);
  add_image_size('grid_8 square', 760, 760, TRUE);
  add_image_size('grid_10', 960);
  add_image_size('grid_12', 1160, FALSE);   
}

Is there a build-in wordpress method to output a random image size?

Thanks

1

I don't think there exists such function in the WordPress core.

Example #1

But you can try something like this:

/**
 * Random image size
 * @return String Image size
 */
function wpse_random_image_size()
{
    $sizes = (array) get_intermediate_image_sizes();
    return $sizes[array_rand( $sizes )];    
}

to display a random image size.

Usage:

if ( function_exists( 'wpse_random_image_size' ) )
    echo wpse_random_image_size();

Example #2

If you want to exclude certain image sizes, e.g. thumbnail and medium then you can use:

/**
 * Random image size     
 * @param  Array | String  Sizes to exclude
 * @return String          Image size
 */
function wpse_random_image_size( $exclude = '' )
{
    $sizes = array_diff( (array) get_intermediate_image_sizes(), (array) $exclude );
    return $sizes[array_rand( $sizes )];    
}

Usage:

if ( function_exists( 'wpse_random_image_size' ) )
    echo wpse_random_image_size( $exclude = ['thumbnail', 'medium' ] );
  • Great, thanks! As far I understand get_intermediate_image_sizes() returns all available image sizes. Is it possible to return specified (desired) image sizes only? – p2or Sep 9 '15 at 12:17
  • It should return the available image sizes. It contains the intermediate_image_sizes filter that might change it. The data comes from the global $_wp_additional_image_sizes array. Do you mean constructing the $sizes array by hand? – birgire Sep 9 '15 at 12:36
  • Makes sense, thanks again. I mean (just for the sake of completeness) How can I control which image sizes to output? E.g. In case I only want to output 3 of 7 custom image sizes... Hope that's a better explanation :) – p2or Sep 9 '15 at 12:46
  • I updated the answer with an exclude example @poor – birgire Sep 9 '15 at 12:48
  • great, you're welcome @poor – birgire Sep 9 '15 at 12:54

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.