# Selective Thumbnail Regenerator

A WordPress plugin that allows users to regenerate thumbnails for media files uploaded in specific months and years - with advanced filtering, performance tuning, and full regeneration history tracking.

## Description

The Selective Thumbnail Regenerator plugin provides a powerful and user-friendly way to regenerate image thumbnails for WordPress media libraries. Unlike other thumbnail regeneration plugins that blindly process the entire library, this plugin gives you precise control: choose a specific year, month, and even a title keyword to target exactly the images you need.

### Key Features

- **Date & Title Filters** - Choose a specific year, month, or search by title to target only the images you need.
- **Month Status Calendar** - A visual 4×3 calendar grid appears when you select a year. Months that have been regenerated are highlighted in green with a checkmark, giving you a permanent at-a-glance overview of your progress. Clicking a month badge automatically selects it.
- **Regeneration History Tracking** - Completed months are stored in the database and persist across sessions. A single "Reset History" button clears all records when needed.
- **Thumbnail Size Selection** - Choose specific registered thumbnail sizes to regenerate instead of processing all sizes.
- **Customizable Batch Size** - Configure how many images are processed per AJAX request (1-20) to suit your server's capacity.
- **Throttle Delay Control** - Set a cooldown pause between batches (0-2000 ms) to prevent server CPU overload.
- **Dry Run Mode** - Preview which images would be processed without writing any changes to disk.
- **Automatic Batch Failure Recovery** - If a batch crashes (PHP fatal error, memory exhaustion, timeout), the plugin automatically retries each image individually to isolate the bad one and continues processing the rest - no manual intervention required.
- **Failed Images Log** - After completion, a detailed table lists every image that failed, including its ID, title, and exact failure reason.
- **Orphaned File Cleanup** - Old thumbnail files are physically deleted from disk before new ones are generated, preventing storage bloat over time.
- **Live Terminal Activity Log** - A real-time monospace console streams timestamped status messages for every operation during the regeneration process.
- **Visual Completion Metrics** - A five-card summary board displays totals for Processed, Successful, Failed, Skipped, and Duration.
- **Performance Optimized** - Uses a direct indexed `$wpdb` SQL query to populate the year selector, eliminating slowdowns on large media libraries.
- **Cancel Support** - Stop the regeneration at any time. The process halts gracefully after the current batch and shows a partial summary.

---

## Installation

1. Download the plugin ZIP file.
2. Log in to your WordPress admin panel.
3. Go to **Plugins > Add New > Upload Plugin**.
4. Upload the ZIP file and click **Install Now**.
5. Activate the plugin through the **Plugins** menu in WordPress.

---

## Usage

1. Navigate to **Tools > Selective Thumbnail Regenerator** in your WordPress admin.
2. **Select a year** from the dropdown. A Month Status Calendar will appear showing which months have already been regenerated.
3. Optionally select a month - either via the dropdown or by clicking a month badge on the calendar.
4. Optionally enter a title keyword to filter images by name.
5. In the Performance Configuration card, adjust the batch size and throttle delay for your server.
6. Enable **Dry Run Mode** if you want to preview results without making changes.
7. Click **Scan Matching Images** to count how many images match your filters.
8. Click **Start Regeneration** to begin. Watch the live terminal log for real-time updates.
9. After completion, review the Job Completion Report and, if any images failed, expand the Failed Images Log.

---

## Requirements

- WordPress 5.5 or higher
- PHP 7.0 or higher

---

## Frequently Asked Questions

### Why would I need to regenerate thumbnails?

You might need to regenerate thumbnails if:
- You've changed your theme and it uses different thumbnail sizes
- You've modified the thumbnail sizes in WordPress settings
- You've installed a plugin that adds new thumbnail sizes
- Your thumbnails are corrupted or missing

### Will this plugin delete my original images?

No. The plugin only regenerates thumbnail versions. Your original uploaded images are never touched.

### What does "orphaned file cleanup" mean?

When thumbnail dimensions change and you regenerate, the old thumbnail files (e.g. `image-300x200.jpg`) remain on disk. This plugin automatically deletes those stale files before writing new ones, keeping your uploads folder clean.

### What happens if an image file is missing from the server?

The plugin detects that the original file is missing, marks it as failed in the log, and moves on to the next image. It never stops the entire regeneration process because of a single missing file.

### What happens if a server error occurs mid-batch?

The plugin automatically enters single-retry mode: it re-processes each image in the failed batch individually. The image causing the crash is identified, logged in the Failed Images report, and skipped so the rest can complete successfully.

### How does Dry Run Mode work?

When Dry Run is enabled, the plugin queries all matching images and logs which ones would be processed - without actually regenerating any thumbnails or writing to disk. History is also not updated during a dry run.

### What is the Month Status Calendar?

It is a 4×3 grid of month badges displayed beneath the date filter. Once a month has been fully regenerated for a given year, its badge turns green with a checkmark. This state is saved in the database and persists across all future sessions. You can reset the history at any time with the "Reset History" button.

### Can I cancel the process?

Yes. Click the **Cancel Process** button that appears during regeneration. The current batch completes first, then the process stops and displays a partial summary.

### What happens if I close the browser during regeneration?

The process stops. AJAX requests are browser-driven, so closing the tab ends the session. You can safely restart from the beginning - already regenerated months will still show as done in the calendar.

---

## Troubleshooting

### "No images found for the selected period"

There are no image attachments in your media library uploaded during the selected year/month. Try a different time period.

### The process is slow

Reduce the throttle delay or increase the batch size in the Performance Configuration card if your server can handle more load. Alternatively, increase the delay and reduce the batch size if you are getting timeouts.

### A batch keeps failing

Enable Dry Run Mode first to verify that images and their files are accessible. If specific images crash the server, they will be listed in the Failed Images Log after regeneration completes.

---

## Changelog

### 1.0.4
- **Critical Fix:** Fixed fatal AJAX error by conditionally loading `wp-admin/includes/image.php` before calling `wp_generate_attachment_metadata()`.
- **Performance Fix:** Replaced PHP loop-based year extraction with a single fast `$wpdb` SQL query.
- **Bug Fix:** Allow thumbnail generation for attachments with missing or corrupt database metadata (graceful empty-array fallback).
- **Cleanup:** Implemented physical deletion of orphaned thumbnail files before regeneration.
- **Feature:** Month Status Calendar - visual 4×3 grid showing regenerated months per year, persisted in the database.
- **Feature:** Regeneration History Tracking with a "Reset History" button.
- **Feature:** Image title search filter.
- **Feature:** Dry Run Mode.
- **Feature:** Configurable Batch Size slider (1-20).
- **Feature:** Configurable Throttle Delay slider (0-2000 ms).
- **Feature:** Automatic batch failure recovery - retries each image individually when a batch crashes.
- **Feature:** Failed Images Log - detailed table of all images that failed with exact error reasons.
- **Redesign:** Full UI overhaul with Inter font, card layout, custom progress bar, live terminal console, and metrics board.

### 1.0.3
- Feature: Thumbnail size selection - choose which specific sizes to regenerate
- Feature: Cancel button - stop the regeneration process at any time
- Feature: Batch processing - process multiple images per AJAX request
- Feature: Summary report - view success/failure counts and elapsed time

### 1.0.2
- Security: Added capability checks to AJAX handlers
- Removed unnecessary plugin assets
- Code structure improvements

### 1.0.1
- Security: Added ABSPATH protection
- Compatibility: Updated "Tested up to" to WordPress 6.8
- Code Standards: Changed all prefixes from `str` to `strgrtr`
- Updated main class name to `STRGRTR_Thumbnail_Regenerator`

### 1.0.0
- Initial release

---

## License

This plugin is licensed under the GPL v2 or later.

## Credits

Developed by Redberet - [https://rberet.com](https://rberet.com) - Adi Glibanovic.