Auto-fill image ALT on upload (only if empty)

/**
* Auto-fill image ALT on upload (only if empty).
* – Derives from attachment title, falling back to filename.
* – Converts “-” and “_” to spaces, collapses whitespace.
* – Caps length around 125 characters (common screen-reader/SEO guidance).
*/
add_action(‘add_attachment’, function ($att_id) {
// Only handle images
if (!wp_attachment_is_image($att_id)) {
return;
}

// Respect any alt already provided (won’t overwrite user edits)
$alt = get_post_meta($att_id, ‘_wp_attachment_image_alt’, true);
if (is_string($alt) && trim($alt) !== ”) {
return;
}

// Prefer the attachment title, else fall back to the filename (without extension)
$title = get_the_title($att_id);
if (!is_string($title) || $title === ”) {
$rel = get_post_meta($att_id, ‘_wp_attached_file’, true); // e.g., 2025/09/photo-1.jpg
$base = $rel ? wp_basename($rel) : (get_attached_file($att_id) ? wp_basename(get_attached_file($att_id)) : ”);
$title = $base ? pathinfo($base, PATHINFO_FILENAME) : ”;
}

// Normalize: dashes/underscores -> space, collapse spaces, trim
$alt = preg_replace(‘/[-_]+/u’, ‘ ‘, $title ?? ”);
$alt = preg_replace(‘/\s+/u’, ‘ ‘, $alt ?? ”);
$alt = trim((string) $alt);

if ($alt === ”) {
$alt = __(‘image’, ‘default’); // final fallback
}

// Cap length ~125 chars
if (function_exists(‘mb_strlen’) ? mb_strlen($alt) > 125 : strlen($alt) > 125) {
$alt = (function_exists(‘mb_substr’) ? mb_substr($alt, 0, 122) : substr($alt, 0, 122)) . ‘…’;
}

update_post_meta($att_id, ‘_wp_attachment_image_alt’, sanitize_text_field($alt));
});

Scroll to Top
Solution lamp for mobile header

Custom Solutions with Zeevou

Discover tailored solutions perfectly suited to your role, business size, and specific use cases.