Created
August 22, 2012 12:00
-
-
Save barryroodt/3424850 to your computer and use it in GitHub Desktop.
Function to auto-resize images already uploaded to WordPress.
This file contains 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
/* | |
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); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.