Contact!

Regenerate WordPress media image sizes, programmatically

Regenerate WordPress media image sizes, programmatically

WordPress comes pre-packaged with several default image sizes which you can use on your site. When you upload an image, WordPress saves several ‘scaled’ versions of the media into your upload folder. As you can imagine, there are several reasons that you might want to regenerate your WordPress media and image sizes. Some common reasons include:

  • Generating thumbnails for a newly added image size.
  • Installing a new theme.
  • Updating and optimising image dimensions.

Here are a couple of approaches, although I advise using a plugin (or you could always use WP-CLI if that is more your boat).

Programatically regenerate media without a plugin

Let’s start programmatically regenerating our WordPress media with a function. We will need to pass it the ID of the image we want to update:

function gb_regenerate($imageId) {

}

The next step is to get the file path of the image using wp_get_original_image_path(). This function returns the file path of the original image (pre-sizing).

function gb_regenerate($imageId) {
    $imagePath = wp_get_original_image_path($imageId);
}

Now that we have the file path and the id, we can use it to regenerate the attachment using wp_generate_attachment_metadata(). As part of generating meta data for the attachment, this function also generates all of the media sizes (which is exactly what we are looking for). The caveat for using this is that wp_generate_attachment_metadata() is an admin function that we don’t normally have access to, therefore we also have to require the correct admin file.

Note: We should validate that we have a correct file path to pass to the function.

require_once(ABSPATH . 'wp-admin/includes/image.php');

function gb_regenerate($imageId) {
    $imagePath = wp_get_original_image_path($imageId);

    // A sprinkle of validation
    if ($imagePath && file_exists($imagePath)) {
        wp_generate_attachment_metadata($imageId, $imagePath);
    }
}

So we have a function here which regenerates media, except you might have noticed that it still doesn’t work. The reason for this is simple; load order. Unfortunately we need certain parts of WordPress to have been loaded in order to get this to run. Time to refactor and find a hook to use!

The hook we are going to use is called ‘init’ which defers running the function until after WordPress has finished loading.

require_once(ABSPATH . 'wp-admin/includes/image.php');

// Put the function in a class to make it more extendable
class GB_regen_media {
    public function gb_regenerate($imageId) {
        $imagePath = wp_get_original_image_path($imageId);

        if ($imagePath && file_exists($imagePath)) {
            wp_generate_attachment_metadata($imageId, $imagePath);
        }
    }
}

// Add a load function
function gb_regen_load() {
    // Instantiate the class
    $gb_regen_media = new GB_regen_media();

    // Set the image Id
    $imageId = 1;

    // You can get the image Id from the url of the media screen
    $gb_regen_media->gb_regenerate($imageId);
}

// Load after WordPress has finished loading
add_action('init', 'gb_regen_load');

Regenerate using a plugin

I don’t often recommend many plugins, but there are a handful out there which I consider very useful. One such plugin is Regenerate Thumbnails. This handy little plugin will regenerate WordPress media on your site so that you don’t have to replace/re-add it yourself.

Sadly the author of this plugin, Alex Mills, has passed away from Leukaemia. If you find this plugin useful then perhaps you might consider donating to Oregon Health & Science University in his memory.

Note: The plugin is open source and currently maintained by members of the WordPress community.

Join the discussion!

You might like:

Create, register and use shortcodes in WordPress

Create, register and use shortcodes in WordPress

by Gav 18/03/2023

Learn how to create and register your own WordPress shortcodes to add dynamic content to your posts and pages.

How to use guard clauses in JavaScript

How to/why use guard clauses in JavaScript

by Gav 16/03/2023

Learn how to improve code readability and performance by using guard clauses in JavaScript. Discover their benefits and best practices.

Implements and Extends, Object Oriented TypeScript

Implements and Extends, Object Oriented TypeScript

by Gav 15/03/2023

Learn the difference between implements and extends in TypeScript. Use Implements to implement interfaces and types, and extends to inherit from classes.

Reading/Parsing and Writing YAML files in PHP, Symfony

Reading/Parsing and Writing YAML files, PHP Symfony

by Gav 14/03/2023

In this tutorial we will look at using YAML in PHP. Learn about Parsing and Writing YAML files using Symfony's YAML component.

Measuring code execution performance in JavaScript

Measuring code execution performance in JavaScript

by Gav 13/03/2023

Measuring code execution performance is an important way to identify bottlenecks. Use these methods in JavaScript to help optimise your code.

Measuring script/code execution time in PHP using microtime

Measuring script/code execution time in PHP, microtime

by Gav 06/03/2023

Find bottlenecks, optimise and clean your code, and speed up your apps by measuring the execution time of your PHP scripts using microtime.

Regenerate WordPress media image sizes, programmatically

Regenerate WordPress media image sizes, programmatically

by Gav 25/02/2021

Learn how to regenerate and update WordPress media and image sizes both programmatically (without plugin), and also with a handy plugin.

Magic Constants in PHP. What they are and how to use them.

Magic Constants in PHP. What they are and how to use them

by Gav 15/02/2021

Ever seen constants like __DIR__ and __FILE__ being used in PHP? These are 'Magic Constants', and this is how we can use them.

Detecting Keypress JavaScript

Detect single and multiple keypress events: JavaScript

by Gav 16/10/2019

Learn how to use event listeners to detect and handle single and multiple keypress events in JavaScript. Add modifier keys to your application!