25% off ProSNIPC25OFF

Auto-Set Image Alt Text from Filename

Automatically populates the alt text meta for newly uploaded images using the sanitized attachment filename.

PHPby SnipCraft
php
<?php
if ( ! function_exists( 'scseed_auto_alt_from_filename' ) ) {
    function scseed_auto_alt_from_filename( $post_id ) {
        $alt = get_post_meta( $post_id, '_wp_attachment_image_alt', true );
        if ( ! empty( $alt ) ) {
            return;
        }
        $slug       = get_post_field( 'post_name', $post_id );
        $clean_name = ucwords( str_replace( array( '-', '_' ), ' ', $slug ) );
        update_post_meta( $post_id, '_wp_attachment_image_alt', sanitize_text_field( $clean_name ) );
    }
    add_action( 'add_attachment', 'scseed_auto_alt_from_filename' );
}
#accessibility#images#media#seo