Halloween Sale 15% off Ends in See the plans
PHP

"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.

Don’t have WPIDE yet? Install it on your site

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

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.