Learn how to add Alt Text for Images automatically in WordPress using a simple PHP function to improve SEO and accessibility.
Alt Text for Images
Alt Text for Images is one of the most important yet often overlooked aspects of WordPress SEO. Whether you run a blog, business website, WooCommerce store, or portfolio, properly optimized image ALT text helps search engines understand your images while making your website more accessible to users who rely on screen readers.
The challenge is that many WordPress websites contain hundreds or even thousands of images without ALT attributes. Editing every image manually can take hours or even days. Fortunately, you can automate the process with a lightweight PHP function that adds missing ALT attributes without changing your Media Library or database.
In this guide, you’ll learn why Alt Text for Images matters, how the provided PHP function works, and how to use it safely on your WordPress website.
What Is Alt Text for Images?
Alt Text for Images (alternative text) is a short description added to an HTML image using the alt attribute.
Example:
<img src="flower.jpg" alt="Beautiful flower garden"> The ALT text serves several important purposes:
- Helps search engines understand image content.
- Improves website accessibility for visually impaired visitors.
- Displays descriptive text if an image fails to load.
- Supports Google Image Search rankings.
- Enhances overall on-page SEO.
Without descriptive ALT text, search engines have limited information about your images, which may reduce their visibility in search results.
Why Alt Text Is Important for SEO
Search engines cannot interpret images the same way humans do. They rely on surrounding content, filenames, structured data, and especially the ALT attribute.
Adding Alt Text for Images provides several SEO benefits:
- Better image indexing
- Increased visibility in Google Images
- Improved page relevance
- Enhanced accessibility compliance
- Better user experience
- Stronger overall website optimization
Although ALT text alone won’t guarantee higher rankings, it contributes to a healthier SEO strategy when combined with quality content, optimized filenames, fast loading speeds, and responsive design.
Common Reasons Images Don’t Have ALT Text
Many WordPress websites have missing ALT attributes because:
- Images were uploaded without descriptions.
- Content was imported from another platform.
- Themes output images without ALT attributes.
- Third-party plugins don’t include ALT text.
- Website owners forgot to optimize older posts.
- External images don’t contain ALT information.
Instead of fixing every image manually, you can automate the process.
Automatically Add Alt Text for Images in WordPress
The following PHP function detects every image on your website that is missing an ALT attribute and automatically generates one.
The function checks the following sources in order:
- Existing Media Library ALT text
- Attachment title
- Uploaded filename
- External image filename
If an image already contains an ALT attribute, it is left untouched.
function jk_fix_img_alt($html) {
return preg_replace_callback('/<img\b[^>]*>/i', function ($matches) {
$img = $matches[0];
// Skip if ALT already exists
if (preg_match('/\balt=["\'][^"\']*["\']/i', $img)) {
return $img;
}
// Get image source
if (!preg_match('/src=["\']([^"\']+)["\']/i', $img, $src_match)) {
return $img;
}
$src = $src_match[1];
$attachment_id = attachment_url_to_postid($src);
$alt = '';
// WordPress Media Library image
if ($attachment_id) {
// 1. Existing Media Library ALT
$alt = get_post_meta($attachment_id, '_wp_attachment_image_alt', true);
// 2. Attachment Title
if (empty($alt)) {
$alt = get_the_title($attachment_id);
}
// 3. File name
if (empty($alt)) {
$file = get_attached_file($attachment_id);
if ($file) {
$alt = pathinfo($file, PATHINFO_FILENAME);
}
}
} else {
// External image
$path = wp_parse_url($src, PHP_URL_PATH);
$alt = pathinfo($path, PATHINFO_FILENAME);
}
// Cleanup text
$alt = str_replace(array('-', '_'), ' ', $alt);
$alt = trim(preg_replace('/\s+/', ' ', $alt));
if (empty($alt)) {
return $img;
}
// Add ALT only
return preg_replace(
'/<img/i',
'<img alt="' . esc_attr($alt) . '"',
$img,
1
);
}, $html);
} How This Function Works
Whenever WordPress generates a page, the function scans every HTML <img> tag.
For each image, it first checks whether an ALT attribute already exists. If one is found, nothing changes.
If the ALT attribute is missing, the function attempts to generate meaningful text using the image’s existing metadata.
For Media Library images, it uses the stored ALT text first. If none exists, it falls back to the attachment title. If the title is also empty, it creates ALT text from the uploaded filename.
For external images, it extracts the filename from the image URL.
Finally, it replaces hyphens and underscores with spaces, producing clean, readable ALT text.
How to Install the Function
Adding this function to your website is straightforward.
- Open your active theme’s functions.php file or use a custom plugin.
- Paste the PHP function.
- Connect it to your preferred output buffer or content filter.
- Save the file.
- Clear your WordPress cache and CDN cache.
- Refresh your pages and inspect images without ALT attributes.
From that point onward, missing ALT attributes are added automatically during page generation.
Benefits of Using This Method
Compared to manually editing images, this solution offers several advantages.
- Automatically adds missing ALT attributes.
- Leaves existing ALT text unchanged.
- Works with Media Library images.
- Supports external image URLs.
- Does not modify your database.
- Requires minimal server resources.
- Improves accessibility.
- Enhances image SEO.
- Produces clean and readable ALT text.
Comparison of Different Methods
| Method | Automatic | Database Changes | Existing ALT Protected | External Images | Easy to Use |
|---|---|---|---|---|---|
| Manual editing | No | Yes | Yes | Yes | No |
| SEO plugins | Partial | Usually | Yes | Limited | Yes |
| SQL updates | Yes | Yes | Sometimes | No | Medium |
| PHP function | Yes | No | Yes | Yes | Yes |
Best Practices for Alt Text for Images
To maximize SEO benefits:
- Upload images with descriptive filenames.
- Write unique ALT text whenever possible.
- Avoid stuffing keywords into every image.
- Keep descriptions relevant to the image.
- Use modern image formats like WebP.
- Compress images for faster loading.
- Continue optimizing important images manually.
These practices help search engines understand your content while improving user experience.
Frequently Asked Questions
Will this overwrite existing ALT text?
No. Images that already contain ALT attributes remain unchanged.
Does this modify the WordPress database?
No. The function only changes the HTML output when pages are generated.
Can it generate ALT text for external images?
Yes. It uses the filename from the image URL.
Is this compatible with WooCommerce?
Yes. Standard WooCommerce product images are supported because they use regular HTML image tags.
Does this improve accessibility?
Yes. Visitors using screen readers can better understand images that previously lacked ALT attributes.
Can I remove the function later?
Yes. Since it doesn’t update the database, simply removing the function restores the original behavior.
Conclusion
Adding Alt Text for Images is one of the easiest ways to improve your WordPress website’s SEO and accessibility. Instead of manually editing hundreds of images, this PHP function automatically generates meaningful ALT attributes using existing Media Library data, attachment titles, or filenames.
Because it preserves existing ALT text, doesn’t modify the database, and even supports external images, it’s a practical solution for websites of any size. If you’re looking for a quick and reliable way to optimize images, this method can save significant time while helping search engines better understand your content.
External Resources
| Resource | Link |
| WordPress Developer Documentation | https://developer.wordpress.org/ |
| Google Search Central Image SEO | https://developers.google.com/search/docs/appearance/google-images |
| W3C Images Accessibility Guide | https://www.w3.org/WAI/tutorials/images/ |
| HTML Image Element Reference | https://developer.mozilla.org/docs/Web/HTML/Element/img |







