Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Generate image sizes on the fly for WordPress
* Create an image with the desired size on-the-fly.
* @param $image_id
* @param $width
* @param $height
* @param $crop
* @return array
function lazy_image_size($image_id, $width, $height, $crop) {
// Temporarily create an image size
$size_id = 'lazy_' . $width . 'x' .$height . '_' . ((string) $crop);
add_image_size($size_id, $width, $height, $crop);
// Get the attachment data
$meta = wp_get_attachment_metadata($image_id);
// If the size does not exist
if(!isset($meta['sizes'][$size_id])) {
require_once(ABSPATH . 'wp-admin/includes/image.php');
$file = get_attached_file($image_id);
$new_meta = wp_generate_attachment_metadata($image_id, $file);
// Merge the sizes so we don't lose already generated sizes
$new_meta['sizes'] = array_merge($meta['sizes'], $new_meta['sizes']);
// Update the meta data
wp_update_attachment_metadata($image_id, $new_meta);
// Fetch the sized image
$sized = wp_get_attachment_image_src($image_id, $size_id);
// Remove the image size so new images won't be created in this size automatically
return $sized;

This comment has been minimized.

Copy link

dmrqx commented Oct 30, 2015

Thank you very much for your contribution!
I'm using this on a new WP theme I'm making for a client and it was very helpful ;)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.