How to Dynamically Resize WordPress Images on the Fly with TimThumb

If you are developing WordPress themes, you already know about add_image_size() to crop your images. This is a best way to crop images in WordPress. But what you will do, if you have thousands of images or posts and want to change a different theme now. Obviously, new theme will come with different image sizes than the previous one. One possible way is to regenerate your thousands of images to work with existing theme’s image sizes, we have already discussed about thumbnail regeneration in our previous article How to Rebuild All WordPress Images. But it will take too much time. So why not, we should go with another simple method and that method is TimThumb.

TimThumb is a small php script for cropping, zooming and resizing web images (jpg, png, gif). Perfect for use on blogs and other applications.

Let’s Start

Download the TimThumb Class from here and paste in a PHP file with a name timThumb.php. Upload you file in your new theme’s directory.

We’ll work inside post loop. So, first get the post’s featured image URL.

How to get post’s featured image URL

[code type=”php”]
$attachment = wp_get_attachment_image_src( $post->ID);
$attachment_url = $attachment[0];
[/code]

Now we have the URL for featured image and you have already uploaded timthumb class file. Let’s say, your new theme design has height (128) and width (128) for image.

[code type=”php”]
<img src=”<?php get_bloginfo(‘stylesheet_directory’); ?>/timThumb.php?src=<?php echo $attachment_url; ?>&h=128&w=128″ width=”128″ height=”128″ />
[/code]

Final Code

[code type=”php”]
<?php while(have_posts()) : the_post();

$attachment = wp_get_attachment_image_src( $post->ID);

$attachment_url = $attachment[0];
?>

<img src=”<?php get_bloginfo(‘stylesheet_directory’); ?>/timThumb.php?src=<?php echo $attachment_url; ?>&h=128&w=128″ width=”128″ height=”128″ />

<?php endwhile; ?>
[/code]

Duan Lingxin

Duan Lingxin

Content crafter and chief editor at Scratching Info. Also regular contributor on other major online tech platforms. Security Specialist by day and a writer by night, he does his best to instill his knowledge about tech while delivering inspiring and life changing resources through his writing,

More Posts - Website

Leave a Comment