Skip to content

Instantly share code, notes, and snippets.

@bpb54321
Last active August 15, 2016 14:55
Show Gist options
  • Select an option

  • Save bpb54321/8eea8b194d1b4da30fd8875bd84bf915 to your computer and use it in GitHub Desktop.

Select an option

Save bpb54321/8eea8b194d1b4da30fd8875bd84bf915 to your computer and use it in GitHub Desktop.
Helper function for getting widths and url's of all the available sizes of an image in WordPress.
/**
* Helper function for getting the widths and url's of all the available crops of an image.
* @param Number $id: The id of the image that you need the info for
* @return Array An associative array with array["widths"] containing an array of widths and array["urls"] containing the corresponding image urls.
*/
function get_image_widths_and_urls($id) {
//Get all the possible image sizes
$image_size_array = get_intermediate_image_sizes();
//error_log('--------------------$image_size_array------------------------');
//error_log( var_export($image_size_array, true) );
$image_width_array = [];
//$image_url_array = [];
$widths_and_urls = [];
$i = 0;
foreach ( $image_size_array as $image_size_name ) {
$image_info_array = wp_get_attachment_image_src($id, $image_size_name);
$image_url = $image_info_array[0];
$image_width = $image_info_array[1];
if ( $image_width >= 300 ) { //Don't want to include any images smaller than 300px, since they won't really ever be useful
$image_width_array[] = $image_width;
$widths_and_urls[$i] = [
"width" => $image_width,
"url" => $image_url,
];
//error_log('--------------------$image_info_array------------------------');
//error_log( var_export($image_info_array, true) );
$i++;
}
}
array_multisort ($image_width_array, SORT_ASC, SORT_NUMERIC, $widths_and_urls); //Sorts $widths_and_urls by the "width" key
return $widths_and_urls;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment