Skip to content

Instantly share code, notes, and snippets.

@daveyjones
Last active June 20, 2023 16:03
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save daveyjones/fe87d99be3d9f0ca4b7786ee5b66c15f to your computer and use it in GitHub Desktop.
Save daveyjones/fe87d99be3d9f0ca4b7786ee5b66c15f to your computer and use it in GitHub Desktop.
Insanely fast multi-core Node.js script for generating (or regenerating) custom WordPress image sizes (e.g. thumbnails) for very large media libraries
// Your server must have wp-cli installed (http://wp-cli.org/)
var async = require("async");
var exec = require("child_process").exec;
var cores = 32; // Adjust the number of cores to match your environment
var total = 0;
var finished = 0;
var q = async.queue(function(task, callback) {
exec(task.command, function(error, stdout, stderr) {
finished++;
process.stdout.write("Processing " + total + " images using " + cores + " cores. Progress: " + (100 * (finished / total)).toFixed(2) + "%\r");
callback();
});
}, cores);
q.drain = function() {
console.log("Finished processing " + total + " images using " + cores + " cores. ");
process.exit();
};
// Get all media post IDs
exec("wp db query \"SELECT id FROM wp_posts WHERE post_type = 'attachment'\"", {maxBuffer: 1000 * 1024}, function(error, stdout, stderr) {
var id = stdout.split(/\n/);
for (var i = 1; i < id.length; i++) {
q.push({command: "wp media regenerate " + id[i]});
total++;
}
});
@daveyjones
Copy link
Author

Run this script from the root of your WordPress installation.

@richardtvaughan
Copy link

Thank you, great work.

@pierrerocket
Copy link

My apologies for being a dingus. Shell is not my strong suit, and I would hate to screw up my site. So I just want to confirm the process here. I have wp-cli installed.

So drop the regenerate-thumbnails.js into the root of the wp site. Then just run this in shell?

node regenerate-thumbnails.js

Is that the gist of it?

@gillesgoetsch
Copy link

gillesgoetsch commented Feb 6, 2020

Awesome! This still works. Install the npm modules first (npm install async, npm install child_process). This is a rocket. Then run node regenerate-thumbnails.js in the root. Thank you.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment