Put alt text into images that are missing alt text to improve SEO rankings of WordPress sites

SEO experts encourage their customers to ensure every image that displays on their website have alt tags with meaningful and descriptive text.  This will help with SEO.  So, what should you do to improve your rankings in the meantime.  Perhaps you have hundreds of images and this will take some time.  Well, this is not a replacement for doing things right.  Get in the habit of adding properly descriptive “alt” text with each image!

Still, you can put this code into your WordPress active child theme’s function.php file for a temporary fix.  This script will comb through each post’s images, find the “<img” tag and look for an “alt” attribute and put in the title of the post in the image it finds.  Not a bad fix as long as the image in the post corresponds to the title, right?!

function img_alt_tags($content){

global $post;
preg_match_all('/<img (.*?)/>/', $content, $images);
if(!is_null($images)) {foreach($images[1] as $index => $value)
{if(!preg_match('/alt=/', $value)){
$new_img = str_replace('<img', '<img alt="'.get_the_title().'"', $images[0][$index]);
$content = str_replace($images[0][$index], $new_img, $content);}}}
return $content;
}
add_filter('the_content', 'img_alt_tags', 99999);

About Author:

Senior Cloud Software Engineer and 25+ years experienced video production, video editing and 3D animation services for a variety of global clients including local video production here in Jacksonville, Florida.

Leave a Comment

Your email address will not be published. Required fields are marked *