# AI Auto Alt Text Generator

A WordPress plugin that writes accessible, SEO-friendly **alt text and image titles** for your media library using **OpenAI**, **Claude (Anthropic)** or **DeepSeek** vision models. Before writing, it looks at where each image is used, so descriptions fit the page.

**External services used:** the one AI provider you choose. See "External services" in [`readme.txt`](readme.txt) for endpoints, data sent, and terms and privacy links.

---

**Plugin Name:** AI Auto Alt Text Generator
**Author:** [Connor Bulmer](https://connorbulmer.co.uk)
**Version:** 2.0.1
**Stable tag:** 2.0.1
**Tested up to:** WordPress 7.1
**Requires at least:** WordPress 5.5 · **Requires PHP:** 7.4
**License:** GPL v3 or later
**Tags:** alt text, accessibility, SEO, images, AI, OpenAI, Claude, DeepSeek, WooCommerce

---

## ✨ Features

- Automatic alt text (and an optional title) on upload
- One-click "Generate Alt Text & Title" button in the Media Library
- Bulk updater for existing images. It replaces missing or filename-style alt text and never overwrites real descriptions.
- **Choice of provider and model:**

  | Provider | Models |
  |---|---|
  | OpenAI | GPT-6 Luna (default, fastest & cheapest), GPT-6.1 Sol, GPT-5.6 Luna, GPT-5.6 Terra |
  | Anthropic | Claude Haiku 5.5, Claude Sonnet 5.5, Claude Opus 5.5 |
  | DeepSeek | DeepSeek V4.1 Flash |

- **Context-aware:** the plugin passes the page title, nearest heading, surrounding text and caption of where the image is used. For WooCommerce products it also passes the product name, categories and short description.
- Alt text and title come from **one request**, which keeps cost and wait time low.
- Images are **embedded in the request** by default, so it works on local, staging and private sites. Public URL delivery is optional.
- Large images are scaled down to 2048 px and compressed to stay under 4 MB, and AVIF/HEIC images are converted to WebP when the server supports it.
- API keys are masked once saved, or can be defined in `wp-config.php`.
- Output in English (US/UK) and 20+ other languages.
- Developer filters and actions, signed outgoing webhooks, and a WordPress Abilities API ability (WP 6.9+)

---

## 🧠 How it works

1. The plugin takes the image at your chosen size, after WordPress has created the resized versions.
2. It gathers short context:
   - where the image is used (embedded in a post, set as a featured image, or attached to a parent post)
   - WooCommerce product details
   - your site name and optional site context
   - optionally, the file name
3. It sends one request to your chosen model. The model describes only what is visible and uses the context to choose relevant terms.
4. The alt text is saved to `_wp_attachment_image_alt`. The title, if enabled, is saved as the attachment title.

---

## 🛠 Installation

1. Upload the plugin to `/wp-content/plugins/ai-auto-alt-text-generator`, or install it from the Plugins screen.
2. Activate it.
3. Go to **Settings → Alt Text Generator**.
4. Pick a provider and model, paste that provider's API key, and save.

To keep keys out of the database, define them in `wp-config.php`:

```php
define( 'AATG_OPENAI_API_KEY', 'sk-…' );
define( 'AATG_ANTHROPIC_API_KEY', 'sk-ant-…' );
define( 'AATG_DEEPSEEK_API_KEY', 'sk-…' );
```

---

## ⚙️ Settings overview

| Option | Description |
|---|---|
| **AI provider / Model** | OpenAI, Anthropic (Claude) or DeepSeek, and one of its vision models |
| **API keys** | One per provider. Masked once saved: leave blank to keep, tick "Remove saved key" to delete |
| **Output language** | English (US) by default, plus English (UK) and 20+ others |
| **Automatically generate image title** | Writes a title in the same request |
| **Use page context** | Sends where the image is used plus WooCommerce product details (on by default, about 600 characters max) |
| **Site context** | Optional notes about your site, audience or brand voice |
| **Send image file name** | Adds the file name as context (on by default for new installs; camera names like `IMG_1234` are skipped) |
| **Image size to send** | Thumbnail, Medium, Large (default) or Full |
| **Image delivery** | Embed the image (default) or send its public URL |
| **Image detail quality** | Low / High (OpenAI and DeepSeek) |
| **Bulk batch size / delay** | Rate-limit controls for bulk runs |
| **Request timeout** | 10–120 s. Timeouts, 429s and overloads are retried once |
| **Webhook URL & secret** | POST each result to your endpoint, with an optional HMAC signature |

---

## 🧩 For developers

- **Filters:**
  - `aatg_generate_on_upload` (return `false` to stop automatic generation on upload)
  - `aatg_models`
  - `aatg_alt_text_prompt`, `aatg_image_title_prompt`
  - `aatg_image_context`
  - `aatg_request_payload`
  - `aatg_openai_request_payload` (OpenAI and DeepSeek)
  - `aatg_api_key`
  - `aatg_provider_endpoint`
  - `aatg_generated_alt_text`, `aatg_generated_title`
  - `aatg_is_low_quality_alt`
  - `aatg_webhook_payload`
  - `aatg_supported_image_extensions`
  - `aatg_max_image_bytes`
- **Actions:** `aatg_after_alt_text_generated`, `aatg_after_title_generated`, `aatg_after_generation`
- **Ability:** `ai-auto-alt-text/generate-alt-text` (input: `attachment_id`)

### Local development

`dev/` holds a Docker test site and integration tests, and is not shipped in the release zip. It includes WordPress 7.1, WooCommerce and a mock AI server that imitates all three APIs.

```bash
dev/setup.sh   # start the site at http://localhost:8091
dev/test.sh    # run the integration tests
```

See [`dev/README.md`](dev/README.md) for details, including how to run a live smoke test with your own keys.

---

## 📦 Changelog

## 2.0.1 2026-11-09
- 🧩 **More robust reply parsing:** JSON followed by text containing `}`, or alternative keys like `alt`, no longer ends up as raw alt text
- 🗜️ **Images over the 4 MB cap are compressed, then scaled down,** instead of being sent oversize. PNG/GIF compress to WebP, keeping transparency. New `aatg_max_image_bytes` filter.
- 🔤 **Invalid UTF-8** in page text or site context is cleaned instead of emptying the context (no more PHP 8.1+ deprecation notices)
- 🔑 **Blank key fields** keep the saved key only on the settings page. `wp option update` stores exactly what you give it.

## 2.0 2026-10-21
- 🤖 **New providers:** Claude (Haiku 5.5, Sonnet 5.5, Opus 5.5) and DeepSeek V4.1 Flash, alongside OpenAI
- 🚀 **Current OpenAI models:** GPT-6 Luna (the new default), GPT-6.1 Sol, GPT-5.6 Luna and Terra. Sites on retiring models (GPT-4o mini, GPT-5 / GPT-5.4 mini and nano) are moved to the cheaper GPT-6 Luna automatically.
- 🧭 **Page context:** uses the page title, nearest heading, surrounding text and caption of where the image is used, plus WooCommerce product details
- 🖼️ **Embedded images:** works on local, staging and private sites. Large images are scaled down, and AVIF/HEIC are converted.
- ⚡ **One request** for alt text and title, and one retry on 429/overload errors
- 🎯 **Grounded output:** place and person names are used only when a caption or product says the image shows them, the context is never mentioned, and alt text stays under 125 characters
- 🏷️ **File names on by default for new installs**, skipping camera names like `IMG_1234`. Upgraded sites keep their setting.
- 🐛 **Fixed:** the "Image size to send" setting was ignored on upload, so the full original was always sent
- 🔐 **Security:**
  - masked keys, with optional `wp-config.php` constants
  - admin-only bulk runs, and a per-image permission check
  - escaped bulk log
  - `wp_safe_remote_post` for webhooks
  - removed the public debug log
- 🧹 **Code:**
  - split into `includes/` and `assets/`
  - every setting validated
  - an uninstall cleanup
  - Docker integration tests
- ✅ Tested up to WordPress 7.1

## 1.22 2026-06-10
- 🛡️ Skip unsupported image formats (SVG, BMP, TIFF, AVIF, HEIC, …) before sending to OpenAI — avoids failed HTTP 400 requests and error-log spam; only PNG, JPEG, GIF and WebP are sent. New `aatg_supported_image_extensions` filter

## 1.21 2026-06-09
- 🚀 New default model: GPT-5.4 nano (fastest & cheapest, vision-capable); GPT-5.4 mini available for higher quality. Existing installs keep their current model; legacy GPT-4o mini and GPT-5 models remain selectable
- ✅ WordPress 7.0 compatibility (tested up to 7.0)
- 🧩 WordPress Abilities API: registers `ai-auto-alt-text/generate-alt-text` (WordPress 6.9+) for core AI, agents and automation
- 🔔 Outgoing webhooks with optional HMAC-SHA256 signature
- 🪝 Developer filters & actions for prompts, payload, output and webhook
- 🔁 Bulk tool now also regenerates filename-based / low-quality alt text, never overwriting genuine descriptions
- ♿ Prompts rewritten for stronger accessibility (WCAG) and SEO; alt text tightened to ~125 characters
- ✨ Media Library “Generate Alt Text & Title” button now updates the fields instantly (no page refresh needed)

## 1.20 2026-03-25
- 🐛 Fixed: Resolved an uncommon issue where generated alt text could include the parent page/post title; prompt now explicitly instructs the model to omit it

## 1.19 2026-02-02
- ⏱️ Added configurable OpenAI request timeout setting (10–120 seconds, default 30)
- 🔁 OpenAI requests now retry once after timeout with an extended timeout window
- 🛟 Reduces transient `cURL error 28` timeout failures during alt text/title generation

## 1.18 2026-01-28
- 🎨 New branded tabbed dashboard with Settings, Bulk Updater, and Integrations panels
- 🧾 Bulk updater now includes a scrollable error/warning log per image
- 🧯 Improved OpenAI error handling surfaced in the UI
- 🚦 Added rate-limit controls (batch size + delay) and set image detail to Low by default
- 🧮 Fixed bulk counter to avoid double counting images without alt text
- ✂️ Trims stray leading quotes from generated alt text and titles

## 1.17 2025-09-09
- 🤖 Added OpenAI model selector with GPT-4o mini default and GPT 5 Mini/Nano (BETA) options

## 1.16 2025-09-09
- 📖 Added language selector to enable outputs in multiple languages, currently supporting the more mainstream languages, but with room to grow in the future
- Improved UX and findability of settings and bulk optimisation in a few places

## 1.15 - 2025-07-29
- 🌐 Various tweaks to help get the plugin listed in the WP repo

## 1.14 - 2025-05-07
- ⏲️ Added option to adjust delay and set the new default delay to 2 seconds (from 5 seconds), it would be worth checking your RPM/RPD [here](https://platform.openai.com/docs/models/gpt-4o-mini) to make sure you do not hit rate limits

### 1.13 – 2025-05-06
- ✅ Fixes for bulk update not working on some versions of MySQL

### 1.12 – 2025-05-01
- ✅ Tweaks to bulk update
- ✅ Various code cleanups and tweaks to work towards getting this on WP.org

### 1.11 – 2025-04-23
- ✅ Added checkbox for full site context for image title generations

### 1.10 – 2025-04-23
- 🛠️ Fixed: bulk update tool was prematurely ending after the first batch  
- ✅ `post_status = inherit` now included in remaining-image query  
- ✅ Improved meta-query to detect alt text that is empty **or** whitespace  
- 🧮 Remaining counter is now accurate across all batches  
- 🖱 Bulk update button now disables while the process is running and re-enables on completion

### 1.9 – 2025-04-21
- ✅ Added setting to include the image file name in the prompt
- ✅ Updated prompts to include filename context when enabled
- ✅ Improved plugin description and settings clarity

### 1.8 – 2025-04-21
- 🔐 Security hardening and internal code review
- ✅ Sanitised all option inputs with `sanitize_text_field()`
- ✅ Added nonce verification to all AJAX handlers
- ✅ Escaped all dynamic content in admin HTML output
- ⚙️ Refactored settings page for cleaner registration
- 🛡️ All options now use WordPress Settings API with proper defaults

### 1.7 – 2025-04-20
- 🆕 Real-time bulk update UI with progress bar and debug text
- ✅ AJAX response now includes per-image alt text preview
- 🔄 Bulk update now runs in batches of 5 with 5 5-second delay
- 🧠 Title prompt refined: “Output ONLY the title without extra labels”

### 1.6 – 2025-04-18
- ✅ Full-scan mode: finds all images with missing alt text
- ⚙️ Bulk processor now uses `sleep()` between chunks
- 🕒 Added `set_time_limit(0)` for longer runs
- 💡 Cleaned up AJAX handler logic

### 1.5 – 2025-04-14
- 🆕 Added “Automatically Generate Image Title” option (on by default)
- ✨ New `aatg_generate_image_title()` function
- 🔄 Title generation now integrated into upload and manual triggers

### 1.4 – 2025-04-10
- 📝 Added “Site Context” field (used in both alt and title prompts)
- ⚙️ Major settings refactor: API key, image size, detail level, context

### 1.3 – 2025-04-07
- 🔧 Default image size set to `large`
- 🖼 Added “Image Detail Quality” dropdown: `high` / `low`
- 🧩 Parent post title now included as contextual hint

### 1.2 – 2025-04-03
- 🖱 Added manual “Generate Alt Text” button to Media Library
- ⚙️ AJAX handler for on-demand generation

### 1.1 – 2025-03-28
- ⚙️ Settings page created under Settings → Alt Text Generator
- ✅ OpenAI API key and image size options added

### 1.0 – 2025-03-25
- 🎉 Initial release
- 🧠 Auto-generates alt text on upload using GPT-4o mini
- ✅ Stores output in `_wp_attachment_image_alt`

---

---

## ❓ FAQ

### Which model should I use?
GPT-6 Luna and Claude Haiku 5.5 are fast and cost a fraction of a cent per image, and DeepSeek V4.1 Flash is similarly cheap. For the most detailed descriptions, pick GPT-6.1 Sol, Claude Sonnet 5.5 or Claude Opus 5.5.

### What if I see a 429 rate limit error?
The plugin retries once automatically. If errors continue, lower the bulk batch size, increase the bulk delay, or set Image Detail Quality to **Low**.

### What is sent to the provider?
The image (embedded, or its public URL) and short context: site name, site context, optionally the file name and, with page context on, details of where the image is used. Page context can include text from drafts and private posts. Only the provider you selected receives anything. The plugin stores only the generated text.

### Can I customise the prompt?
Yes. Use the site context setting, the page context and file-name switches, or the `aatg_alt_text_prompt`, `aatg_image_title_prompt` and `aatg_image_context` filters.

---

## 📜 License

This plugin is licensed under the GNU General Public License v3.0 or later.  
See: [https://www.gnu.org/licenses/gpl-3.0.html](https://www.gnu.org/licenses/gpl-3.0.html)

---

> Developed with ❤️ by [Connor Bulmer](https://connorbulmer.co.uk)  
> Accessibility, SEO, and automation — all in one plugin.
