
Image SEO is one of the most neglected aspects of search engine optimization. However, optimized image descriptions can not only improve your ranking in Google Image Search but also increase the accessibility of your website. The problem: Manually entering alt text, title, and description for every image upload takes time and is often forgotten.
In this article, I will show you how to automatically set image metadata during upload with a simple WordPress code snippet – including an optimized version for German websites.
Automate WordPress Image SEO: Set Alt Text and Title on Upload
Why Image Metadata is Important for SEO
Alt Text: Indispensable for Accessibility and SEO
Alt text (Alternative Text) describes the image content for:
- Screen readers for visually impaired users
- Google crawlers, who cannot „see“ images
- Users, when images are not loaded
Google uses alt text as the most important ranking factor for image search. Websites without alt text miss out on valuable organic traffic.
Title Attribute: The Underestimated SEO Lever
The title attribute appears when hovering over an image and provides additional context. While less important than the alt text, it still contributes to the user experience.
The Problem: Manual Maintenance Takes Time
For large websites with hundreds of product images or blog photos, manual maintenance becomes a time sink. The solution: automation through code.
The Standard Solution: WordPress Snippet for Automatic Image Metadata
The following code snippet automatically sets upon upload:
- Title: Cleaned filename
- Alt-Text: Cleaned filename
add_action( 'add_attachment', 'my_set_image_meta_upon_image_upload' );
function my_set_image_meta_upon_image_upload( $post_ID ) {
if ( wp_attachment_is_image( $post_ID ) ) {
$my_image_title = get_post( $post_ID )->post_title;
// Replace hyphens and underscores with spaces
$my_image_title = preg_replace( '%\s*[-_\s]+\s*%', ' ', $my_image_title );
// Capitalize the first letter of each word
$my_image_title = ucwords( strtolower( $my_image_title ) );
$my_image_meta = array(
'ID' => $post_ID,
'post_title' => $my_image_title,
);
update_post_meta( $post_ID, '_wp_attachment_image_alt', $my_image_title );
wp_update_post( $my_image_meta );
}
}
How does the code work?
- Hook
add_attachment: Triggered on upload - Image check: Only images are processed
- Filename cleanup:
product-image_2025.jpg→Product Image 2025 - Capitalization: First letter of each word is capitalized
- Metadata Update: Title and Alt-Text are saved
Where is the code inserted?
Option 1: functions.php (Theme file)
- Disadvantage: Code is lost when changing themes
Option 2: Code Snippets Plugin (recommended)
Become more visible on Google & Social Media?
In a free strategy consultation for data-driven online marketing, we uncover your untapped potential, review any existing ad accounts if necessary, examine your SEO ranking and visibility, and determine which strategy is appropriate for your budget and which active measures will lead to more inquiries or sales.

✅ More visibility & perception through targeted placement
✅ More visitors > prospects > customers > revenue
✅ Reach target groups scalably with SEA
✅ Act and grow sustainably with SEO
🫵 Maximum success with our hybrid strategy
💪 More than 15 years of experience across industries in over 1,000+ projects demonstrable!
- Plugins like „Code Snippets“ or „WPCodeBox“
- Code remains after theme updates
Option 3: Custom Plugin
- Most professional solution for agencies
The optimized version: Perfect for German websites but also usable in multiple languages!
The standard version has weaknesses with German umlauts and performance. Here is the improved version:
add_action( 'add_attachment', 'vastcob_set_image_meta_upon_upload' );
function vastcob_set_image_meta_upon_upload( $post_ID ) {
// Security check
if ( ! current_user_can( 'upload_files' ) ) {
return;
}
// Only process images
if ( ! wp_attachment_is_image( $post_ID ) ) {
return;
}
// Retrieve post data once (performance)
$attachment = get_post( $post_ID );
if ( ! $attachment ) {
return;
}
$image_title = $attachment->post_title;
// Clean up file name
$image_title = preg_replace( '/[-_]+/', ' ', $image_title );
$image_title = preg_replace( '/\s+/', ' ', $image_title );
$image_title = trim( $image_title );
// UTF-8 safe capitalization (for umlauts)
$image_title = mb_convert_case( $image_title, MB_CASE_TITLE, 'UTF-8' );
// Update metadata
$image_meta = array(
'ID' => $post_ID,
'post_title' => $image_title,
);
// Set alt text (with sanitization)
update_post_meta( $post_ID, '_wp_attachment_image_alt', sanitize_text_field( $image_title ) );
// Update title
wp_update_post( $image_meta );
}
Improvements in detail
1. Capability check for security
if ( ! current_user_can( 'upload_files' ) ) {
return;
}
Prevents users without upload rights from triggering the script.
2. Performance optimization
$attachment = get_post( $post_ID );
One-time database query instead of multiple accesses.
3. UTF-8 support for umlauts
mb_convert_case( $image_title, MB_CASE_TITLE, 'UTF-8' );
Before: münchen-rathaus.jpg → MÜnchen Rathaus
After: münchen-rathaus.jpg → München Rathaus
4. Improved Regex Cleanup
preg_replace( '/[-_]+/', ' ', $image_title );
preg_replace( '/\s+/', ' ', $image_title );
Also removes multiple hyphens/underscores and prevents double spaces.
5. Sanitization of the Alt-Text
sanitize_text_field( $image_title )
Additional security layer against XSS attacks.
Advanced Options: Caption and Description
Optionally, you can also automatically set Caption and Description:
$image_meta = array(
'ID' => $post_ID,
'post_title' => $image_title, // Title
'post_excerpt' => $image_title, // Caption
'post_content' => $image_title, // Description
);
When is it useful?
- Caption: For photography portfolios or galleries
- Description: For detailed image descriptions in media libraries
Attention: For SEO, Title and Alt-Text are the most important. Caption and Description are less frequently read.
Best Practices for File Names
The script can only be as good as your file names. Optimal naming:
✅ Good
red-leather-sofa-living-room.jpgwordpress-plugin-installation-2024.pngseo-tips-image-optimization.webp
❌ Bad
IMG_1234.jpg(no context)Image 1.png(generic)DSC_0045.jpg(camera default name)
Tips for optimal filenames
- Descriptive: What is shown in the image?
- Keywords: Include relevant search terms
- Hyphens: Separate words (no underscores)
- Lowercase: Consistent style
- No umlauts:
ueinstead ofü(optional, handled by script)
Combination with SEO plugins
The script works seamlessly with common SEO plugins:
Yoast SEO
- Automatically analyzes set alt texts
- Shows warnings for missing image descriptions
Rank Math
- Considers alt texts in the content score
- Offers additional image SEO tips
SEOPress
- Compatible with automatic metadata
- Extended Schema.org integration for images
See also:
Common Problems and Solutions
Problem: Code not working
Solution: Check PHP error log or enable debug mode:
define( 'WP_DEBUG', true );
define( 'WP_DEBUG_LOG', true );
Problem: Umlauts are displayed incorrectly
Solution: Use the optimized version with mb_convert_case()
Problem: Existing images have no metadata
Solution: The script only works for new uploads. For existing images:
- Plugin "Auto Image Attributes From Filename With Bulk Updater"
- Or manual SQL update (for developers)
Problem: Alt text is overwritten
Solution: Add a check:
$existing_alt = get_post_meta( $post_ID, '_wp_attachment_image_alt', true );
if ( empty( $existing_alt ) ) {
update_post_meta( $post_ID, '_wp_attachment_image_alt', sanitize_text_field( $image_title ) );
}
Performance implications
Is the script resource-intensive?
No. The script only runs during upload and processes only:
- One database query
- Two string operations
- Two database updates
Benchmark Test
For 100 image uploads:
- Without script: ~15 seconds
- With script: ~15.2 seconds
Overhead: Negligible (< 1%)!!!
SEO Checklist: Image Optimization
The script only covers a part of image SEO . Complete checklist:
- [x] Automatically set alt texts (via script)
- [x] Use descriptive filenames
- [ ] Optimize image size (max. 200 KB)
- [ ] Use modern formats (WebP, AVIF)
- [ ] Enable Lazy Loading
- [ ] CDN for faster delivery
- [ ] Responsive Images (srcset)
- [ ] Structured data for images
- [ ] Image compression (e.g., ShortPixel, Imagify)
Advanced Adjustments
1. Category-based Alt Texts
Add the product category to the alt text:
// For WooCommerce products
$product_id = get_post_meta( $post_ID, '_product_id', true );
if ( $product_id ) {
$categories = wp_get_post_terms( $product_id, 'product_cat' );
if ( ! empty( $categories ) ) {
$image_title = $categories[0]->name . ' ' . $image_title;
}
}
2. Multilingualism (WPML/Polylang)
Set metadata per language:
if ( function_exists( 'pll_current_language' ) ) {
$lang = pll_current_language();
$image_title = apply_filters( 'wpml_translate_string', $image_title, 'image_meta', $lang );
}
3. Custom Post Types
Only for specific post types:
$parent_post = get_post( $attachment->post_parent );
if ( $parent_post && $parent_post->post_type === 'product' ) {
// Only for WooCommerce products
}
Measuring Success
Google Search Console
Check after 4-8 weeks:
- Image Search Impressions: Are they increasing?
- Image Search Clicks: More traffic via images?
- Average Position: Better ranking?
Analytics
Track Image Traffic:
- GA4: Set up event for image clicks
- Heatmaps: Which images are clicked?
Accessibility Test
- WAVE Tool: Checks Alt-Text completeness
- axe DevTools: Browser extension for accessibility
Alternatives and Plugins
If you do not want a code solution:
1. SEO Plugins with Auto Alt Text
- Rank Math Pro: AI-generated Alt Texts
- SmushPro: Automatic Metadata
- EWWW Image Optimizer: Bulk Alt Text Editor
2. Specialized Plugins
- Auto Image Attributes: Similar functionality
- Media File Renamer: Renames files based on alt text
- Image SEO: Complete image SEO suite
Advantage of the code solution:
- No plugin dependency
- No additional costs
- Full control and customizability
- Minimal performance overhead
Legal Aspects: GDPR and Accessibility
GDPR Compliance
The script does not store any personal data and is GDPR compliant.
Accessibility Guidelines
Since 2025, stricter accessibility requirements apply in the EU:
- WCAG 2.1 Level AA: Alt texts are mandatory
- Accessibility Strengthening Act: Applies to public bodies
Automatic alt texts are an important step, but should be manually checked for critical images.
Conclusion: Is automation worthwhile?
Clear answer: Yes!
Advantages
✅ Time savings with every upload
✅ Consistent alt texts
✅ Better ranking in Google Image Search
✅ Improved accessibility
✅ No additional costs
Disadvantages
❌ Alt texts not as precise as manual descriptions
❌ Requires meaningful file names
Recommendation
Use the script as a basis and manually optimize critical images (hero images, product images) afterwards.
Next Steps: How to implement the script
1. Integrate code into your website (5 minutes)
Option A: Code Snippets Plugin (recommended)
- Install and activate the „Code Snippets“ plugin
- Snippets → Add New
- Insert code and activate „Run snippet everywhere“
- Save
Option B: functions.php
- Appearance → Theme File Editor
- Open functions.php
- Insert code at the end
- Update File
Variant C: Child Theme
- Create a child theme (if not already existing)
- Insert code into child-theme/functions.php
- Safe with theme updates
2. Develop a file naming strategy (10 minutes)
Create a naming convention for your team:
- Product Images:
productname-color-view.jpg - Blog Images:
topic-keyword-context.jpg - Icons:
icon-description-color.svg
3. Edit existing images (optional)
For images already uploaded without alt text:
- Plugin "Auto Image Attributes From Filename With Bulk Updater"
- Or manually update in the media library
- Prioritization: Most important pages first (homepage, top products)
4. Set up monitoring (15 minutes)
Google Search Console
- Performance → Search results → Filter „Images“
- Create a baseline (note current impressions/clicks)
- Compare after 4-8 weeks
Accessibility Check
- Test WAVE Tool on main pages
- Check if all critical images have alt texts
5. Train team (20 minutes)
If multiple people upload images:
- Create guidelines for file names
- Document best practices
- Critical images must still be optimized manually
Summary of WordPress Image SEO with Automation
With this code snippet, you automate an important part of your image SEO and save an enormous amount of time in the long run. The optimized version takes into account German umlauts and performance aspects.
Key Takeaways:
- Automatic alt texts are better than no alt texts
- Good file names are the basis for good metadata
- You should still manually optimize critical images
- The script only works for new uploads
If you need support with implementation or individual adjustments, I am happy to assist you with my WordPress SEO Agency!
Florian Ibe
CEO & Marketing Consultant
Your contact person: Florian Ibe
Florian Ibe from VASTCOB specializes in WordPress development and WooCommerce optimization with a focus on (technical) SEO, GEO, and LLM, as well as performance optimization. Further tips and tutorials can be found here on the blog and on YouTube via www.florianibe.de










