Fill Missing Alt Text From the File Name
When an image is uploaded without alt text, creates one from its title (based on the file name), replacing dashes and underscores with spaces.
Opens WPIDE on
Code
add_action( 'add_attachment', function ( $attachment_id ) {
if ( ! wp_attachment_is_image( $attachment_id ) ) {
return;
}
if ( '' !== (string) get_post_meta( $attachment_id, '_wp_attachment_image_alt', true ) ) {
return;
}
$alt = trim( preg_replace( '/[\s_-]+/', ' ', (string) get_the_title( $attachment_id ) ) );
if ( '' !== $alt ) {
update_post_meta( $attachment_id, '_wp_attachment_image_alt', sanitize_text_field( ucfirst( $alt ) ) );
}
} );
Notes
Generated alt text is only as good as the file name. Review it for important images.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.