Enhance WordPress Image Accessibility Without Plugins

Enhance WordPress Image Accessibility Without Plugins

Are you looking to boost your WordPress website's Accessibility by ensuring your images have proper alt text and titles? Here’s a quick script you can employ without the need for additional plugins.

/* Automatically set the image Title & Alt-Text upon upload*/
add_action( 'add_attachment', 'set_image_meta_upon_image_upload' );
function set_image_meta_upon_image_upload( $post_ID ) {
    // Check if uploaded file is an image, else do nothing
    if ( wp_attachment_is_image( $post_ID ) ) {
        $my_image_title = get_post( $post_ID )->post_title;
        // Sanitize the title: remove hyphens, underscores & extra spaces
        $my_image_title = preg_replace( '%\s*[-_\s]+\s*%', ' ',  $my_image_title );
        // Sanitize the title: capitalize first letter of every word (other letters lowercase)
        $my_image_title = ucwords( strtolower( $my_image_title ) );
        // Create an array with the image meta (Title, Caption, Description) to be updated
        $my_image_meta = array(
            'ID'        => $post_ID,            // Specify the image (ID) to be updated
            'post_title'    => $my_image_title,     // Set image Title to sanitized title
        );
        // Set the image Alt-Text
        update_post_meta( $post_ID, '_wp_attachment_image_alt', $my_image_title );
        // Set the image meta (e.g. Title, Excerpt, Content)
        wp_update_post( $my_image_meta );
    }
}        

This script automatically sets the image Title and Alt-Text upon upload, ensuring improved accessibility for your site. It sanitizes the titles and ensures proper formatting, making your images more accessible to all users.

#WordPress #Accessibility #WebDevelopment #ImageOptimization #freelance


To view or add a comment, sign in

More articles by Rajan Gupta

Explore content categories