Skip to content

Instantly share code, notes, and snippets.

@jrobinsonc
Last active August 29, 2015 14:04
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jrobinsonc/77f4deed418631ccef52 to your computer and use it in GitHub Desktop.
Save jrobinsonc/77f4deed418631ccef52 to your computer and use it in GitHub Desktop.
Wordpress filter: image_downsize
<?php
/**
* Default:
*/
$post_thumbnail_id = get_post_thumbnail_id(get_the_ID());
$width = 640;
$height = 480;
$image_obj = wp_get_attachment_image_src($post_thumbnail_id, array($width, $height));
printf('<img src="%s" width="%u" height="%u">', $image_obj[0], $image_obj[1], $image_obj[2]);
/**
* Other options:
*/
$post_thumbnail_id = get_post_thumbnail_id(get_the_ID());
$width = 640;
$height = 480;
$crop = true; // See WP_Image_Editor reference for cropping options.
$quality = 85;
$image_obj = wp_get_attachment_image_src($post_thumbnail_id, array($width, $height, $crop, $quality));
printf('<img src="%s" width="%u" height="%u">', $image_obj[0], $image_obj[1], $image_obj[2]);
<?php
add_filter('image_downsize', function ($false, $attachment_id, $size)
{
if (!wp_attachment_is_image($attachment_id))
return FALSE;
//---------------------------------------------------
$upload_dir = wp_upload_dir();
$size_string = is_array($size)? "{$size[0]}x{$size[1]}" : $size;
$img_metadata = wp_get_attachment_metadata($attachment_id);
// If indicated size not exist:
if (!isset($img_metadata['sizes'][$size_string]))
{
// If $size is an Array, it will be used to create the new image.
if (is_array($size))
{
$img_full_path = "{$upload_dir['basedir']}/{$img_metadata['file']}";
$image = wp_get_image_editor($img_full_path);
if (is_wp_error($image))
return FALSE;
if (isset($size[3]))
$image->set_quality($size[3]);
$crop = isset($size[2])? $size[2] : TRUE;
$image->resize($size[0], $size[1], $crop);
$result = $image->save();
if (is_wp_error($result))
return FALSE;
$img_metadata['sizes'][$size_string] = array(
'file' => $result['file'],
'width' => $result['width'],
'height' => $result['height'],
'mime-type' => $result['mime-type']
);
wp_update_attachment_metadata($attachment_id, $img_metadata);
}
// Otherwise, return false.
else
{
return FALSE;
}
}
$img_full_url = "{$upload_dir['baseurl']}/{$img_metadata['file']}";
$img_resized_url = str_replace(wp_basename($img_metadata['file']), $img_metadata['sizes'][$size_string]['file'], $img_full_url);
$is_intermediate = TRUE;
return array(
$img_resized_url,
$img_metadata['sizes'][$size_string]['width'],
$img_metadata['sizes'][$size_string]['height'],
$is_intermediate
);
}, 10, 3);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment