How To Use wp_get_image_editor Method To Resize Your Images In WordPress

In the early days of my career, I was using external libraries to resize the images in WordPress. I did not know about built-in WordPress provided function wp_get_image_editor resize. Use of external library for resizing images was a kind of complex task. Thanks to WordPress for providing the method wp_get_image_editor which makes a developer life much easy.

Why We Need To Resize Image

Resizing of images is a very important factor in terms of site performance, site speed. If you are uploading the image with the dimension of 1000px*500px and space available to display this image on site is 300px*120px, then we should resize the original image to the desired dimension. By this way, you can speed up your site.

To make your page load faster, you should resize and compress site images. You can read our articles on optimizing images How To Optimize Image On Upload In PHP and TinyPNG Compress Images Using PHP.

Use Of wp_get_image_editor() Method

Use of wp_get_image_editor is very easy and straight-forward. You need to pass absolute path of an image which you want to resize. Below is the sample code which you can refer as per your needs. In my case I am resizing image ‘site-logo.png’ which located in my themes directory under the ‘images’ folder. I name my new resize image to ‘new-logo.png’.

$img_path = get_stylesheet_directory() . '/images/';
$img_name = 'site-logo.png';
$image = wp_get_image_editor( $img_path . $img_name );
if ( ! is_wp_error( $image ) ) {
    $image->resize( 200, 50, true );
    $image->save( $img_path . 'new-logo.png' );
}

I have passed width and height to 200px and 50px respectively. Notice the third parameter which I set to true. It means image will be hard-cropped to the passed dimensions. If this parameter is false then image will resize proportionally.

I hope you understand how to use wp_get_image_editor to resize your images in WordPress. For any questions or suggestions please leave a comment below.

If you liked this article, then please subscribe to our YouTube Channel for video tutorials.

5 thoughts on “How To Use wp_get_image_editor Method To Resize Your Images In WordPress

  1. Hello friend, I do not understand very well in what WordPress file should I leave it, in functions.php? and the other thing is that I need to do it but images by lot not one by one as explained here

    1. Yes, you can put this code in functions.php or create a separate page template for it. Please note if you are doing it from functions.php then comment the code after the first run. And for multiple images, you need to build logic to get multiple images and resize one by one. Use the glob function and then for loop.

Leave a Reply

Your email address will not be published.