WordPress release 3.5 came with a neat Image Editing API : scaling, resizing, cropping, rotating, flipping, setting image quality, etc… you name it ! Well, as this makes it so much easier to manipulate and transform images, I thought I’d give it a try to create post thumbnails.
I’m going to use this image (600×400 px) as an example – it reminds me of a great holiday vacation in the Galapagos islands…
Let’s say I want a 200×200 thumbnail. All I’ll need is to resize and probably crop the image, so I’ll only be using a tiny amount of the given possibilities. For more details, you might want to read the whole desciption of the WP_Image_Editor class.
If your theme supports thumbnails (aka “featured images”), and one is availble. you could easily use the wordpress built-in function that provides a thumbnail. You might do this :
1 2 3 |
$width = 200; $height = 200; get_the_post_thumbnail($post_id, array($width,$height) ); |
The only drawback is you don’t end up with a 200×200 image. You get an image resized to 200×133, that is a maximum size of 200 and scale is preserved.
Ok, so this is where the WP image editor API will prove usefull. Let’s say we have our image ready for use in the wordpress uploads folder, in this case : “wp-content/uploads/2013/04/”
We simply create a WP_Image_Editor instance, resize and crop, and finally save the result for later use ! How much easier can it get ? Take a look at the sample code
1 2 3 4 |
$file = 'igunana.jpg'; $image = wp_get_image_editor( ABSPATH . 'wp-content/uploads/2013/04/' . $file ); // create instance $image->resize(200,200,true); // resize and crop : width=200, height=200, crop=true $image->save( ABSPATH . 'wp-content/uploads/myThumbnails/' . $file ); // save to custom folder |
The crop function cuts off equal parts on the left and right hand sides of the image. I would leave it like that as a default usage, but for those who want to crop differently, that is of course possible using the $image->crop()
method. It’s all up to you !
Anyway, there you go ! If you need more details, you may ask by leaving a comment, I’ll be pleased to help.