Skip to content

Instantly share code, notes, and snippets.

@barryroodt
Created August 22, 2012 12:00
Show Gist options
  • Save barryroodt/3424850 to your computer and use it in GitHub Desktop.
Save barryroodt/3424850 to your computer and use it in GitHub Desktop.
Function to auto-resize images already uploaded to WordPress.
/*
Place inside your functions.php
Example usage inside template: echo jt_get_image(get_the_ID(), 'my-image-size');
*/
function jt_get_image($post_id, $size='post-thumbnail')
{
global $_wp_additional_image_sizes;
$thumb = get_post_meta($post_id, "_thumbnail_id", true);
$fullsizepath = get_attached_file( $thumb );
$filesource = wp_get_attachment_image_src($thumb, $size);
if (!$filesource[1] || !$filesource[2] || $filesource[1] > $_wp_additional_image_sizes[$size]['width'] || $filesource[2] > $_wp_additional_image_sizes[$size]['height'])
{
$metadata = wp_generate_attachment_metadata( $thumb, $fullsizepath );
wp_update_attachment_metadata( $thumb, $metadata ); // regenerates all thumbnails for this image
}
return wp_get_attachment_image($thumb, $size);
}
@barryroodt
Copy link
Author

The problem with using WordPress's "add_image_size()" function is that the new size is not applied to any existing images.
Use this function if you've added/created a new theme and need to resize previously uploaded images on the fly.
The resize portion should only be applied to the image if the required image size doesn't already exist.

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