WordPress function to create resized images in custom dimensions

In the world of WordPress themes, the resize_image_from_url function is a little magic wand for your images. Imagine you’ve got a stunning, high-resolution photo that’s perfect for desktop viewers, but it’s a bit too hefty for your mobile audience. This clever function steps in to resize that image on-the-fly, making it just the right size for different screens while keeping everything looking sharp. Whether you need a perfectly scaled-down version for speedy mobile loading or a full-size beauty for desktop, this function has you covered. It’s all about making your site not only beautiful but also super user-friendly and efficient, no matter where your audience is tuning in from.

I’m particularly fond of this script as it provides the necessary image-resizing functionality without the need for a plugin. With it, you can resize your images in a couple of different ways:

  • You can define both a width and height, effectively cropping the image into those dimensions.
  • You can define only the width, or only the height, and the image will scale to resize, keeping its original dimensions.

To use the script, add the following to your functions.php file:

function resize_image_from_url($imageUrl, $targetWidth = null, $targetHeight = null) {
    $tempImage = tempnam(sys_get_temp_dir(), 'downloaded_');
    if (!copy($imageUrl, $tempImage)) {
        return 'Error downloading image.';
    }
    list($originalWidth, $originalHeight, $imageType) = getimagesize($tempImage);
    if (is_null($targetWidth) && !is_null($targetHeight)) {
        $aspectRatio = $originalWidth / $originalHeight;
        $targetWidth = intval($targetHeight * $aspectRatio);
    } elseif (!is_null($targetWidth) && is_null($targetHeight)) {
        $aspectRatio = $originalHeight / $originalWidth;
        $targetHeight = intval($targetWidth * $aspectRatio);
    } elseif (is_null($targetWidth) && is_null($targetHeight)) {
        $targetWidth = $originalWidth;
        $targetHeight = $originalHeight;
    }
    switch ($imageType) {
        case IMAGETYPE_GIF:
            $sourceImage = imagecreatefromgif($tempImage);
            break;
        case IMAGETYPE_JPEG:
            $sourceImage = imagecreatefromjpeg($tempImage);
            break;
        case IMAGETYPE_PNG:
            $sourceImage = imagecreatefrompng($tempImage);
            break;
        default:
            unlink($tempImage); 
            return 'Unsupported image type.';
    }
    $newImage = imagecreatetruecolor($targetWidth, $targetHeight);
    if (!$newImage) {
        imagedestroy($sourceImage); 
        unlink($tempImage); 
        return 'Error creating new image.';
    }
    imagecopyresampled($newImage, $sourceImage, 0, 0, 0, 0, $targetWidth, $targetHeight, $originalWidth, $originalHeight);
    $upload_dir = wp_upload_dir();
    $fileInfo = pathinfo($imageUrl);
    $resizedImageName = 'resized_' . $fileInfo['filename'] . '-' . $targetWidth . 'x' . $targetHeight . '.' . $fileInfo['extension'];
    $resizedImagePath = $upload_dir['path'] . '/' . $resizedImageName;
    switch ($imageType) {
        case IMAGETYPE_GIF:
            if (!imagegif($newImage, $resizedImagePath)) return 'Error saving GIF image.';
            break;
        case IMAGETYPE_JPEG:
            if (!imagejpeg($newImage, $resizedImagePath)) return 'Error saving JPEG image.';
            break;
        case IMAGETYPE_PNG:
            if (!imagepng($newImage, $resizedImagePath)) return 'Error saving PNG image.';
            break;
    }
    imagedestroy($sourceImage);
    imagedestroy($newImage);
    unlink($tempImage);
    return $upload_dir['url'] . '/' . $resizedImageName;
}

Next, to use the function to create dynamically resized versions of your images, open up the template file where you want to display the image.

If you want to resize the Featured Image:

$post_id = get_the_ID();
$featured_image_url = get_the_post_thumbnail_url($post_id);
if ($featured_image_url) {
    $resized_featured_image_url = resize_image_from_url($featured_image_url, 200, 200); // width and height
    $resized_featured_image_url_width = resize_image_from_url($featured_image_url, 200); // width only
    $resized_featured_image_url_height = resize_image_from_url($featured_image_url, null, 200); // height only
    echo '' . get_the_title($post_id) . '';
}

This example shows how to resize an image URL saved to a custom field:

$image = get_post_meta(get_the_ID(), 'custom_field_image', true);
$resizedImage = resize_image_from_url($image, 200, 200 ); // width and height 
$resizedImageWidth = resize_image_from_url($image, 200 ); // only width 
$resizedImageHeight = resize_image_from_url($image, null, 200 ); // only height