Skip to main content
Login Join
Snippet · PHP

Auto Generate Image Alt Text

Shared by Darshit Rajyaguru · May 14, 2026 · @add_attachment

31 views
Back to Snippets

Sets image alt text automatically from uploaded filename.

add_action( 'add_attachment', function( $attachment_id ) {

	if ( ! wp_attachment_is_image( $attachment_id ) ) {
		return;
	}

	$title = get_the_title( $attachment_id );
	$alt = preg_replace( '/[-_]+/', ' ', $title );
	update_post_meta( $attachment_id, '_wp_attachment_image_alt', sanitize_text_field( $alt ) );
} );
Know a different way to do this? Add your approach as a variation so folks can compare them side by side.
Submit a variation

0 comments