"Regenerate Sizes" Link for a Single Image
Adds a "Regenerate sizes" link under each image in the Media Library list that rebuilds all its thumbnails, useful after changing image sizes or fixing a bad crop, without a plugin.
Opens WPIDE on
Code
add_filter( 'media_row_actions', function ( $actions, $post ) {
if ( wp_attachment_is_image( $post ) && current_user_can( 'edit_post', $post->ID ) ) {
$actions['wpide_regen'] = sprintf(
'<a href="%s">Regenerate sizes</a>',
esc_url( wp_nonce_url( admin_url( 'admin-post.php?action=wpide_regenerate_image&attachment=' . $post->ID ), 'wpide_regen_' . $post->ID ) )
);
}
return $actions;
}, 10, 2 );
add_action( 'admin_post_wpide_regenerate_image', function () {
$id = isset( $_GET['attachment'] ) ? absint( $_GET['attachment'] ) : 0;
check_admin_referer( 'wpide_regen_' . $id );
if ( ! current_user_can( 'edit_post', $id ) || ! wp_attachment_is_image( $id ) ) {
wp_die( 'Not allowed.', 403 );
}
$file = wp_get_original_image_path( $id );
$ok = false;
if ( $file && file_exists( $file ) ) {
require_once ABSPATH . 'wp-admin/includes/image.php';
$meta = wp_generate_attachment_metadata( $id, $file );
$ok = ! empty( $meta ) && ! is_wp_error( $meta ) && wp_update_attachment_metadata( $id, $meta );
}
wp_safe_redirect( add_query_arg( 'wpide_regen', $ok ? 'done' : 'failed', admin_url( 'upload.php?mode=list' ) ) );
exit;
} );
add_action( 'admin_notices', function () {
if ( isset( $_GET['wpide_regen'] ) ) {
echo 'done' === $_GET['wpide_regen']
? '<div class="notice notice-success is-dismissible"><p>Image sizes regenerated.</p></div>'
: '<div class="notice notice-error is-dismissible"><p>Could not regenerate this image: the original file is missing.</p></div>';
}
} );
Notes
Old size files that are no longer registered stay on disk; for whole-library runs use "wp media regenerate" in WP-CLI.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.