-
-
Save jauhari/6ff8a4dd226d1799c124f2df5ef5c0be to your computer and use it in GitHub Desktop.
Generate image sizes on the fly for WordPress
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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 | |
remove_image_size($size_id); | |
return $sized; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment