Home / Admin / Add Image Alt Text automatic
Duplicate Snippet

Embed Snippet on Your Site

Add Image Alt Text automatic

Code Preview
php
<?php
function add_alt_text_to_images( $html ) {
    // Check if the image has a title attribute
    if ( preg_match( '/(title=["\'].*?["\'])/', $html, $matches ) ) {
        // Get the title
        $title = substr( $matches[0], 7, -1 );
        // Check if the image has an alt attribute
        if ( ! preg_match( '/(alt=["\'].*?["\'])/', $html ) ) {
            // Add the alt attribute with the same value as the title
            $html = preg_replace( '/(title=["\'].*?["\'])/', '$1 alt=' . $title . ' ', $html );
        }
    }
    return $html;
}
add_filter( 'the_content', 'add_alt_text_to_images' );

Comments

Add a Comment