Skip to content

Early-bird lifetime licence: $199 once, for the first 200 buyers only. See the offer

Alt text from the file name

When you upload an image without alt text, it gets one made from its file name (“red-summer-dress.jpg” becomes “Red summer dress”). Better than none; edit it for the best results.

  • Type PHP
  • Runs Everywhere (runs as WordPress loads)
  • Category Media
  • Tested with WordPress 7.1
PHP
<?php

add_action(
	'add_attachment',
	static function ( $attachment_id ) {
		if ( ! wp_attachment_is_image( $attachment_id ) || get_post_meta( $attachment_id, '_wp_attachment_image_alt', true ) ) {
			return;
		}
		$name = pathinfo( (string) get_attached_file( $attachment_id ), PATHINFO_FILENAME );
		$name = preg_replace( '/-(scaled|rotated|\d+x\d+|e\d{10,})$/', '', $name );
		$text = trim( preg_replace( '/[\s_-]+/', ' ', (string) $name ) );
		if ( '' !== $text && ! preg_match( '/^(img|dsc|image|photo|screenshot)?\s*\d*$/i', $text ) ) {
			update_post_meta( $attachment_id, '_wp_attachment_image_alt', ucfirst( $text ) );
		}
	}
);

Good to know

Camera names like IMG_1234 are skipped: an empty alt is better than a meaningless one.

In these packs

  • Images and media: Sharper, lighter images, tidier uploads and a more useful media library.

Move your snippets over this afternoon.

Importing changes nothing until you switch over, and your old shortcodes keep working.