• Resolved mayazir

    (@mayazir)


    I recently made some changes to my WordPress site. Previously, I switched between a few themes that had plugins cropping uploaded images into multiple sizes.

    I recently created my own WordPress theme and plugins. In the process, I cleaned up my media library by deleting all images, as previous themes and plugins had generated a lot of unnecessary image sizes.

    Here’s what my media library structure looked like before:

    2021 > 01 > image-one.jpg
    image-one-150×150.jpg
    image-one-300×300.jpg
    image-one-500×500.jpg

    2021 > 02 > image-two.jpg
    image-two-150×150.jpg
    image-two-300×300.jpg
    image-two-500×500.jpg

    2021 > 03 > image-three.jpg
    image-three-150×150.jpg
    image-three-300×300.jpg
    image-three-500×500.jpg

    I deleted all images from the media library, so currently, I have no images in the gallery. My custom theme only keeps the original image size (850x600px) and generates a smaller version (500x353px).

    Using image resizing software, I re-created all the images with the same file names but resized dimensions and uploaded them back into their original wp-content/uploads folders (organized by year and month) using FTP.

    2021 > 01 > image-one.jpg
    image-one-500×353.jpg

    2021 > 02 > image-two.jpg
    image-two-500×353.jpg

    2021 > 03 > image-three.jpg
    image-three-500×353.jpg

    I then uploaded these images back to the original year and month folders using FTP (e.g., wp-content/uploads/2021/01, 2021/02, etc.).

    Question:

    Is there any way to make these images show up in the WordPress media library again, while keeping them organized in their respective year and month folders?

    My goal is to re-register all the images in the media library and automatically set the re-uploaded images as featured images for the posts they were originally assigned to.

    Is there an easy way to achieve this?

Viewing 15 replies - 1 through 15 (of 19 total)
  • Moderator bcworkz

    (@bcworkz)

    How did you delete all the old images? The media library works by maintaining image meta data in the DB. If that data is intact, uploading replacement files via FTP using the exact same paths and names would ensure the library continues to work. However, you’ve at least altered some file names, even if it’s just the dimensional part of the file name. Thus you’d need to update the related DB meta data accordingly.

    If you permanently deleted images via the media library’s UI, then all the related meta data has been deleted as well. It would need to be regenerated by uploading images anew, which would involve new year/month folders. Alternately, restore the deleted meta data from a DB backup.

    The best way to accomplish what you wish to do here is to properly define all of your desired image sizes, either via your theme or the WP media sizes UI. Then use a regenerate thumbnails type of plugin to create all of the proper image sizes. Such a plugin would need at least the full size images and related meta data in order to properly create the various sizes. For specifics on what such a plugin does and what its prerequisite data is, I recommend asking for guidance through the plugin’s dedicated support channel.

    Thread Starter mayazir

    (@mayazir)

    Yes, I have deleted all images from the gallery but I have all backups.
    I didn’t change the name of the original images, but yes, I created their smaller versions.

    For example, previously I had

    image-001
    image-001-150×150
    image-001-250×250
    image-001-300×300

    And then I removed all cropped images and kept only the original image-001 and added there image-001-500×353 which I creted using image resizing software.

    Moderator bcworkz

    (@bcworkz)

    Assuming the related DB records still exist (or were restored from backup), the problem is the downsized image file names no longer match the file names in the DB. The image-001-300×300.jpg file named in the DB no longer exists, having been replaced by image-001-500×353.jpg. So in order for the image-001-500×353.jpg image to be available for use by the media library, the related DB record needs to be updated to match. Not only does the file name change, but the saved dimensional data must also be updated.

    You likely have too many images to ever consider doing this manually. Even if there are only a few, the data exists in serialized array format. Manually editing a serialized array is not recommended unless you are intimately familiar with the required structural syntax.

    If you’re unwilling to re-upload the images into new year/month folders, your best course of action IMO is to make use of a regenerate thumbnails type of plugin to generate all the down sized images from the original full size image. Most importantly, such a plugin will also update the related DB records. This will cause the images you’ve already resized to be overwritten. It’s likely your resized image quality is superior to that done by your server’s image processing module. Assuming the regenerate thumbnails plugin creates the exact same file names and dimensions as you’ve done yourself, you could re-upload your images via FTP, replacing those automatically generated by the plugin.

    Thread Starter mayazir

    (@mayazir)

    Thanks, I will try to search for a plugin or create a script to regenerate thumbnails.

    My functions.php has this:

    function disable_default_image_sizes($sizes) {
    unset($sizes[‘thumbnail’]);
    unset($sizes[‘medium’]);
    unset($sizes[‘large’]);
    unset($sizes[‘medium_large’]);
    unset($sizes[‘1536×1536’]); // Additional sizes in recent WP versions
    unset($sizes[‘2048×2048’]); // Additional sizes in recent WP versions
    return $sizes;
    }
    add_filter(‘intermediate_image_sizes_advanced’, ‘disable_default_image_sizes’);

    My theme uses “large” or “full” images and “medium” only.

    So, for each NEW site, each uploaded image creates only 1 smaller copy, not a cropped image.
    I use to upload images of 850×600, so each uploaded image will have a smaller version of 500×353.

    For the ALREADY EXISTING sites, I need to create all those smaller versions manually.
    One of my sites has 1500 images and many of them are used in another sites with good DA and I don’t want to lose those backlinks, so I can’t just reupload each of 1500 images to 1050 posts.

    • This reply was modified 1 month, 4 weeks ago by mayazir.
    • This reply was modified 1 month, 4 weeks ago by mayazir.
    • This reply was modified 1 month, 4 weeks ago by mayazir.
    Moderator bcworkz

    (@bcworkz)

    A regenerate thumbnails plugin should generate all the smaller images, there’s no need to do so manually. Only if the automatic version’s image quality is unsatisfactory should you need to manually make smaller images. Hopefully there will not be too many of those, if any at all.

    I don’t want to lose those backlinks, so I can’t just reupload each of 1500 images to 1050 posts.

    Understandable, but there will be the same problem either way since the filenames change due to different dimensions. Even worse, finding all references to an image in post content may not be so easy. We can identify which post an image was initially uploaded for in its attachment properties, but when the same image is reused elsewhere, the only way to find such instances is to do an overall post content search. Even then, such a search will not find instances where an image is used outside of content, such as for header backgrounds or similar.

    In some cases, images used outside of post content will be automatically updated when the attachment metadata is updated. In other cases you might need to manually update specific references.

    I’m unsure how well a regenerate thumbnails plugin will do in updating image references anywhere in the DB. I expect it to update attachment metadata, but beyond that IDK.

    Thread Starter mayazir

    (@mayazir)

    Let’s talk about the exact sites.
    I have a few small sites where I use images 850×600, and I can easily re-upload there all these images, I have time and these sites have as many 50-250 images and only 40-80 posts.

    But my site MexicanRoutes(.com) has more than 1500 images and 1050 posts.
    I use images of 850×425 for this site, and the site creates additional cropped images of 80×80, 150×150, 300×150, 320×320, 520×245, 720×340, and 768×384.

    Each post uses the original 850×425 image as a feature image, some posts have images in the content – all these images are also only the original, not cropped, and not smaller versions.

    The site also has category pages, and I think somewhere else the theme uses cropped images or smaller versions of the original.
    No of these images are backlinked, all backlinked images are images that were used as feature images – original ones.

    The theme that I want to use on this site, is used here – CampecheCity(.com).
    The theme creates only 1 smaller version.
    The small version is used in category pages and in sidebars.
    Posts’s feature images are original uploaded images.

    I can create this small version using image resize soft, but this image will have a new name – the name that was not in the DB previously.

    I just need to learn how to do this task on a few of my small sites to be sure I can do it on my big site.

    If that doesn’t work, I have one last option – don’t use smaller images at all. I mean the theme will use only “full” or “large” images. In this case, I only can delete all cropped and smaller versions and keep only the original image in each directory.

    • This reply was modified 1 month, 3 weeks ago by mayazir.
    Moderator bcworkz

    (@bcworkz)

    Featured images rely upon image metadata in the DB to establish the image’s URL, so as long as the metadata’s filenames have been updated (via a plugin perhaps), featured images are good to go.

    Full size images whose filenames contain no size information will also be good to go since their current URLs remain unchanged. It’s only the downsized images with size information in the filename which are problematic. If all the sizes are consistent in both height and width, it’s possible to do a regex search and replace to update all the filenames throughout the DB. However, often one of the dimensions is typically variable even if the other dimension is consistent. This makes a search and replace operation much more complicated. Not impossible, but complicated.

    I recommend doing a trial run on one of the smaller sites with one of the regenerate thumbnails plugins. First make a backup of your DB. Presumably you already have backups of the images. The full size images should be safe anyway, but the images you manually downsized will likely be overwritten. Be sure you have backups of those.

    TBH, I’ve not used any of these regenerate thumbnails plugins. I cannot recommend any one in particular. What I would expect one to do is to delete all existing downsized images, leaving the full size originals. It would then generate all the downsized images based upon the image sizes currently defined by your site. It should also update all related meta data. Ideally, it would also update any image URLs in post content. Whether a plugin would go this far or not IDK. If you can find a plugin that does everything, then the conversion process should be relatively pain free.

    Thread Starter mayazir

    (@mayazir)

    I will try some of such plugins on my small sites and if I find it too problematic, I better will replace all “medium” images from the theme by “the “full” ones.

    As I already said, my new theme uses “medium” size images only for category pages and sidebar posts.

    Thanks anyway. I will post here the update this or the next week

    Thread Starter mayazir

    (@mayazir)

    I tried to restore images on one of my small sites – TijuanaCity.com.

    I wanted to try some of the plugins you recommended, but I ran into a couple of problems. For some reason, I couldn’t update my WordPress, and the first plugin didn’t work as expected. I suspect this was because I re-uploaded all of my files via SFTP and not vis FTP. Rather than wait for support to reset the file permissions, I decided to ask GPT to help me create a custom plugin for this task.

    So, I deleted everything from the “uploads” folder, and then re-uploaded my files, organizing them by year and month – just like I had them before. I also created smaller versions of each image and placed them in the appropriate folder next to the original files.

    After activating the plugin, I clicked the “magic big blue button” to restore the media. Most of the images were restored and appeared in the media gallery. However, I did run into a small bug where 7 out of 104 images weren’t showing up. Despite this, I was able to find these images by name in the Media Gallery and find them manually.

    In the end, all my original images retained their URLs, but I had to go through each post and add them manually to make sure they were showing up correctly.

    This is a problem… because opening each post on my large sites and adding the appropriate image would be time consuming and nearly impossible since I can’t remember which image was placed in each of the thousands of posts.

    • This reply was modified 1 month, 2 weeks ago by mayazir.
    Moderator bcworkz

    (@bcworkz)

    I had to go through each post and add them manually

    Yeah, that’s the final element I was hoping a plugin would manage for you, but I was skeptical it would happen. IDK if a different plugin would do it, or if you’re stuck with the situation.

    If an image was originally uploaded for a specific post so that the post’s ID appears as the attachment’s parent property, then writing a script to update each post wouldn’t be too cumbersome. But if the same images are reused elsewhere, there’s not much to go on in finding all such references in posts and updating each URL. It’s not impossible to script the task, but it gets a lot more complicated. When there are a lot of such images, it’s probably worth the effort to develop a script to handle the task.

    Or maybe develop a simpler script that only works on posts whose ID appears as parent properties, then handle the rest manually. Hopefully the script would manage the vast majority of images and there will not be too many left to do manually.

    Thread Starter mayazir

    (@mayazir)

    Maybe I should NOT remove images from the Media Library? When I remove smaller copies of the image, the image itself also disappears from the library, but I see a grey background. Maybe I should don’t pay attention on this and after removing all smaller copies, regenerate it all? I will try it tomorrow on one of my other small site.

    Moderator bcworkz

    (@bcworkz)

    Yes, you should not simply remove downsized image files from the server. The media library will still think they exist because it relies upon data in the DB that remains unchanged. The only ways to remove down sized images from the DB is to either completely remove the image from the library via WP UI, then re-upload; or remove undesired image size definitions from source code, then do the regenerate process. The remove then upload process also requires removal of definitions from source code.

    Either way, we still have the problem of image URLs in post content still referring to images that no longer exist. If you cannot find a plugin that updates post content, the corrections will need to be done manually or via custom script.

    Thread Starter mayazir

    (@mayazir)

    I did it.
    Or better say, GPT did it for me.
    MazatlanCity.com – all images on this site were regenerated.

    1. I downloaded the folder “uploads” to my PC, I checked all images to be sure they all were the same size and to be sure there were no accidentally uploaded images from old and cloned sites.
    2. I removed all “extra” images, keeping only the original ones.
    3. I used FSResizer to create smaller versions of each original image and renamed them accordingly. I checked and found that if the original image was 850×450, the smaller version (according to my theme) would be 500×294. I also knew that each smaller image would have the same name as the original + an extra “-500×294”. So I used FSResizer to create the correct images with the correct names in just a few seconds.
    4. I opened the “upload” folder (via FTP) and replaced all old folders by the updated ones.
    5. I did not delete the gray silhouettes of “non-existent” images from the Media Library. It’s important.
    6. I installed the plugin, then clicked on the “Restore Media” button and…

    That’s all.

    I will test it on a few more small sites before I dare to use it on my larger sites.
    I have no idea how to post here the code for the plugin.

    • This reply was modified 1 month, 2 weeks ago by mayazir.
    • This reply was modified 1 month, 2 weeks ago by mayazir.
    • This reply was modified 1 month, 2 weeks ago by mayazir.
    • This reply was modified 1 month, 2 weeks ago by mayazir.
    • This reply was modified 1 month, 2 weeks ago by mayazir.
    • This reply was modified 1 month, 2 weeks ago by mayazir.
    Thread Starter mayazir

    (@mayazir)

    <?php
    /**
    Plugin Name: Regenerate Media Library
    Description: Scans the uploads folder, re-registers only original images in the media library, and regenerates thumbnails.
    */

    if (!defined('WPINC')) {
    die;
    }

    function restore_and_regenerate_media_library() {
    global $wpdb;

    $upload_dir = wp_get_upload_dir();
    $base_dir = $upload_dir['basedir'];

    if (!is_dir($base_dir)) {
    wp_die('Uploads directory does not exist.');
    }

    $files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($base_dir));

    $image_map = [];

    foreach ($files as $file) {
    if ($file->isDir()) {
    continue;
    }

    $file_path = $file->getPathname();
    $relative_path = str_replace($base_dir . '/', '', $file_path);

    if (!preg_match('/(\d{4})\/(\d{2})\//', $relative_path, $matches)) {
    continue;
    }

    $year = $matches[1];
    $month = $matches[2];

    $filetype = wp_check_filetype($file_path);
    if (strpos($filetype['type'], 'image') === false) {
    continue;
    }

    if (preg_match('/-[0-9]+x[0-9]+\.(jpg|jpeg|png|gif)$/', $file_path)) {
    continue;
    }

    $image_name = preg_replace('/\.[^.]+$/', '', basename($file_path));

    $existing_attachment_id = $wpdb->get_var($wpdb->prepare(
    "SELECT ID FROM $wpdb->posts WHERE guid = %s",
    $upload_dir['baseurl'] . '/' . $relative_path
    ));

    if ($existing_attachment_id) {
    $image_map[$image_name] = $existing_attachment_id;
    } else {
    $attachment = [
    'guid' => $upload_dir['baseurl'] . '/' . $relative_path,
    'post_mime_type' => $filetype['type'],
    'post_title' => $image_name,
    'post_content' => '',
    'post_status' => 'inherit',
    'post_date' => "$year-$month-01 12:00:00",
    ];

    $attach_id = wp_insert_attachment($attachment, $file_path);
    require_once ABSPATH . 'wp-admin/includes/image.php';
    $attach_data = wp_generate_attachment_metadata($attach_id, $file_path);
    wp_update_attachment_metadata($attach_id, $attach_data);

    $image_map[$image_name] = $attach_id;
    }
    }

    // Restore featured images
    $posts = $wpdb->get_results("SELECT post_id, meta_value FROM $wpdb->postmeta WHERE meta_key = '_thumbnail_id'");
    foreach ($posts as $post) {
    $old_attachment_id = $post->meta_value;
    $image_title = $wpdb->get_var($wpdb->prepare("SELECT post_title FROM $wpdb->posts WHERE ID = %d", $old_attachment_id));

    if (isset($image_map[$image_title])) {
    update_post_meta($post->post_id, '_thumbnail_id', $image_map[$image_title]);
    }
    }

    // Regenerate thumbnails for all images
    $attachments = get_posts([ 'post_type' => 'attachment', 'numberposts' => -1 ]);
    foreach ($attachments as $attachment) {
    $file_path = get_attached_file($attachment->ID);
    if ($file_path) {
    $attach_data = wp_generate_attachment_metadata($attachment->ID, $file_path);
    wp_update_attachment_metadata($attachment->ID, $attach_data);
    }
    }

    echo 'Media library restoration and thumbnail regeneration completed. Featured images restored where possible.';
    }

    function restore_media_library_page() {
    echo '<div class="wrap"><h1>Restore & Regenerate Media Library</h1>';
    if (isset($_POST['restore_media'])) {
    restore_and_regenerate_media_library();
    }
    echo '<form method="post"><input type="submit" name="restore_media" class="button-primary" value="Restore & Regenerate"></form></div>';
    }

    function restore_media_library_menu() {
    add_management_page('Restore & Regenerate Media Library', 'Restore & Regenerate', 'manage_options', 'restore-media-library', 'restore_media_library_page');
    }
    add_action('admin_menu', 'restore_media_library_menu');
    Moderator bcworkz

    (@bcworkz)

    Awesome! For future reference, we try to discourage the posting of large amounts of code here in the forums. Preferably you would post such code at either pastebin.com or gist.github.com, then simply provide the resulting link here.

Viewing 15 replies - 1 through 15 (of 19 total)
  • You must be logged in to reply to this topic.