mayazir
Forum Replies Created
-
Don’t repeat my error – don’t keep old folders with images in the “upload” folder, remove all unnecessary image files, because the plugin will scan, find and add them too all to the Media Gallery
It took less than 10 seconds to regenerate all on a website with almost default server config.
I tested it on sites with max 350 images.Tested on a medium sized website and it wroks.
<?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');I did it.
Or better say, GPT did it for me.
MazatlanCity.com – all images on this site were regenerated.- 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.
- I removed all “extra” images, keeping only the original ones.
- 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.
- I opened the “upload” folder (via FTP) and replaced all old folders by the updated ones.
- I did not delete the gray silhouettes of “non-existent” images from the Media Library. It’s important.
- 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 year, 3 months ago by mayazir.
- This reply was modified 1 year, 3 months ago by mayazir.
- This reply was modified 1 year, 3 months ago by mayazir.
- This reply was modified 1 year, 3 months ago by mayazir.
- This reply was modified 1 year, 3 months ago by mayazir.
- This reply was modified 1 year, 3 months ago by 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.
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 year, 3 months ago by 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
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 year, 4 months ago by 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.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×300And 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.
Feedback left. Thank you.
It works now, thanks
Thanks, I will do it in a few hours
Yesterday suddenly it stopped counting visits.
I waited 24 hours and updated the plugin and PHP.
But the plugin continued showing ZERO visits.
I deactivated 2 optimization plugins and it seems it started working.
I see 2 visits, but at this time, I usually have no traffic, so I better keep plugins deactivated and check the site in 3-4 hours.
I see you via Wordfence live traffic, and Burst registered 2 visits – me and you.I will activate 1 by 1 both optimization plugins to see which one is the problem.
I’ll check it again in a few hours when there’s traffic because most of the traffic is coming from the US and Mexico – and they’re just waking up now,Thanks