Automate WordPress image SEO: Set alt text + title on upload
WordPress Images SEO Automate Alt Text Title Set on Upload WooCommerce Generate Names Filenames

Bilder-SEO ist einer der am meisten vernachlässigten Aspekte der Suchmaschinenoptimierung. Dabei können optimierte Bildbeschreibungen nicht nur dein Ranking in der Google Bildersuche verbessern, sondern auch die Barrierefreiheit deiner Website erhöhen. Das Problem: Bei jedem Bild-Upload manuell Alt-Text, Title und Beschreibung einzugeben, kostet Zeit und wird oft vergessen.

Contents of this article

In this article, I show you how to automatically set image metadata on upload using a simple WordPress code snippet – including an optimized version for German websites.

WordPress Image SEO Automation: Set Alt-Text and Title during upload

Why image metadata is important for SEO

Alt text: Essential for accessibility and SEO

The alt text (alternative text) describes the image content for:

  • Screen reader for visually impaired users
  • Google crawlers that cannot "see" images
  • Users when images fail to load

Google uses alt texts as the most important ranking factor for image search. Websites without alt texts are wasting 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 alt text, it still contributes to user experience.

The problem: Manual maintenance costs time



For large websites with hundreds of product images or blog photos, manual maintenance becomes time-consuming. The solution: automation through code.

WordPress Image SEO Automate Alt Text Title Upload Generate WooCommerce Set Names Filenames

The standard solution: WordPress snippet for automatic image metadata

The following code snippet automatically sets upon upload:

  • Title: Cleaned file name
  • Alt text: Cleaned file name
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;
        
        // Bindestriche und Unterstriche durch Leerzeichen ersetzen
        $my_image_title = preg_replace( '%\s*[-_\s]+\s*%', ' ',  $my_image_title );
        
        // Ersten Buchstaben jedes Wortes großschreiben
        $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?

  1. Hook add_attachment: Triggered during upload
  2. Image Review: Only images are processed
  3. Filename Cleanup: produkt-bild_2025.jpgProdukt Bild 2025
  4. Capitalization: First letter of each word is capitalized
  5. 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?

Contents of this article

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.

visible-online-marketing-seo-sea-social-media-optimization-consulting-advertising-web

✅ 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!

Request a marketing strategy consultation now

and become sustainably visible!

High Performer Europe Agency Logo
trusted shop partner qualified expert
Google Partner
Bing Ads Microsoft MSA Partner Badge Agency Pictibe
Meta Business Partner Social Media Ads Agency Badge
Seo Top 100
Wa Advertising Agency De
  • Plugins such as "Code Snippets" or "WPCodeBox"
  • Code remains intact during theme updates

Code Snippets

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 ) {
    // Sicherheitsprüfung
    if ( ! current_user_can( 'upload_files' ) ) {
        return;
    }
    
    // Nur Bilder verarbeiten
    if ( ! wp_attachment_is_image( $post_ID ) ) {
        return;
    }
    
    // Post-Daten einmalig abrufen (Performance)
    $attachment = get_post( $post_ID );
    if ( ! $attachment ) {
        return;
    }
    
    $image_title = $attachment->post_title;
    
    // Dateinamen bereinigen
    $image_title = preg_replace( '/[-_]+/', ' ', $image_title );
    $image_title = preg_replace( '/\s+/', ' ', $image_title );
    $image_title = trim( $image_title );
    
    // UTF-8-sichere Großschreibung (für Umlaute)
    $image_title = mb_convert_case( $image_title, MB_CASE_TITLE, 'UTF-8' );
    
    // Metadaten aktualisieren
    $image_meta = array(
        'ID'         => $post_ID,
        'post_title' => $image_title,
    );
    
    // Alt-Text setzen (mit Sanitization)
    update_post_meta( $post_ID, '_wp_attachment_image_alt', sanitize_text_field( $image_title ) );
    
    // Title aktualisieren
    wp_update_post( $image_meta );
}

Improvements in detail

1. Capability check for security

if ( ! current_user_can( 'upload_files' ) ) {
    return;
}

Prevents users without upload permissions from triggering the script.

2. Performance Optimization

$attachment = get_post( $post_ID );

Single 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.jpgMÜnchen Rathaus
After: münchen-rathaus.jpgMünchen Rathaus

4. Improved Regex Cleaning

preg_replace( '/[-_]+/', ' ', $image_title );
preg_replace( '/\s+/', ' ', $image_title );

Also removes multiple hyphens/underscores and prevents double spaces.

5. Sanitization of alt text

sanitize_text_field( $image_title )

Additional security layer against XSS attacks.

Advanced options: Caption and Description

Optionally, you can also set caption and description automatically:

$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 most important. Caption and description are read less frequently.

Best practices for file names

The script can only be as good as your file names. Optimal naming:

✅ Good

  • rotes-ledersofa-wohnzimmer.jpg
  • wordpress-plugin-installation-2024.png
  • seo-tipps-bilder-optimierung.webp

❌ Poor

  • IMG_1234.jpg (no context)
  • Bild 1.png (generic)
  • DSC_0045.jpg (Camera Default Name)

Tips for optimal file names

  1. Descriptive: What can be seen in the image?
  2. Keywords: Incorporate relevant search terms
  3. Hyphens: Separate words (no underscores)
  4. Lowercase: Consistent Style
  5. No Umlauts: ue instead of ü (optional, handled by the 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 text in content score
  • Offers additional image SEO tips

SEOPress

  • Compatible with automatic metadata
  • Enhanced Schema.org Integration for Images

See also:

The best WordPress SEO plugin 😎 Search engine optimization 👌 WordPress & WooCommerce 🔥 Top Rankings 📈



Common problems and solutions

Problem: Code Does Not Work

Solution: Check the 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 being 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 impacts

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

At 100 Image Uploads:

  • Without Script: ~15 seconds
  • With Script: ~15.2 seconds

Overhead: Vernachlässigbar (< 1%)!!!

SEO checklist: Image optimization

The script covers only part of the image SEO. Complete checklist:

  • [x] Set alt text automatically (via script)
  • [x] Use descriptive file names
  • [ ] 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 customizations

1. Category-Based Alt Texts

Add the Product Category to the Alt Text:

// Für WooCommerce-Produkte
$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' ) {
    // Nur für WooCommerce-Produkte
}

Measurement of Success

Google Search Console

Check After 4-8 Weeks:

  • Image search impressions: Are they increasing?
  • Image search clicks: More traffic through 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 text
  • SmushPro: Automatic metadata
  • EWWW Image Optimizer: Bulk Alt Text Editor

2. Specialized Plugins

  • Auto Image Attributes: Similar functionality
  • Media File Renamer: Renames files according to 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 text is mandatory
  • Accessibility Enhancement Act: Applies to public institutions

Automatic alt texts are an important step, but should be manually reviewed for critical images.

Conclusion: Is automation worth it?

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 text not as precise as manual descriptions
❌ Requires Meaningful File Names

Recommendation

Use the script as a basis and optimize critical images (hero images, product images) manually afterwards.

Next Steps: How to implement the script

1. Integrate Code into Your Website (5 Minutes)

Variant A: Code Snippets Plugin (recommended)

  1. Install and activate the "Code Snippets" plugin
  2. Snippets → Add New
  3. Insert code and enable "Run snippet everywhere"
  4. Save

Variant B: functions.php

  1. Appearance → Theme File Editor
  2. Open functions.php
  3. Insert Code at End
  4. Update File

Variant C: Child Theme

  1. Create child theme (if not already present)
  2. Insert code in child-theme/functions.php
  3. Safe with theme updates

2. Develop a file naming strategy (10 minutes)

Create a naming convention for your team:

  • Product Images: produktname-farbe-ansicht.jpg
  • Blog Images: thema-keyword-kontext.jpg
  • Icons: icon-bezeichnung-farbe.svg

3. Edit Existing Images (Optional)

For Already Uploaded Images 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 baseline (note current impressions/clicks)
  • Compare after 4-8 weeks

Accessibility check

  • Test WAVE tool on main pages
  • Check whether all critical images have alt text

5. Train team (20 minutes)

When multiple people upload images:

  • Create guidelines for file names
  • Document best practices
  • Critical images must continue to be manually optimized

Summary of WordPress image SEO with automation

With this code snippet, you automate an important part of your image SEO and save enormous amounts of time in the long run. The optimized version takes German umlauts and performance aspects into account.

Key Takeaways:

  • Automatic alt text is better than no alt text
  • Good file names are the foundation for good metadata
  • You should still manually optimize critical images afterwards
  • The script only works for new uploads

If you need support with implementation or custom modifications, I am happy to assist you with my WordPress SEO Agency!

Personal consultation Florian Ibe CEO & Marketing Consultant Pictibe-Florian-Ibe-Owner-Person-SEO-SEA-Social-Media-Onlinemarketing-small.png VASTCOB Management Consulting Digitalization Advertising Agency Marketing Agency SEO SEA Social Media WordPress WooCommerce

Florian Ibe
CEO & Marketing Consultant

Request a non-binding consultation now:

fi@vastcob.com

Open contact form

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. You can find more tips and tutorials here in the blog and on YouTube at www.florianibe.de

    Florian
    Florian
    has found his calling through passion. Fundamentally honest and direct, he advises everyone from sole proprietors to founders and startups, as well as business and management levels of SMEs. As a consultant, he understands how to reduce complex relationships to their essence and develop a direct message for customers and employees with a sustainable strategy and optimization.

    Leave a Reply

    Your email address will not be published. Required fields are marked *


    Probably the newest best tool & software offers with a lifetime license

    Our recommendation:

    Screenshot of bit.ly

    Pay once for software access & enjoy it for a lifetime