March 21, 2022
Automatically Add ALT+TITLE to Images in the_content() output
This will automatically assign the ALT & TITLE attributes to <img> elements that miss those. The value will be the post title ( aka get_the_title() );
<?php function add_alt_tags($content) { global $post; preg_match_all('/<img (.*?)\/>/', $content, $images); if(!is_null($images)) { foreach($images[1] as $index => $value) { $new_img = $images[0][$index]; if(!preg_match('/alt=/', $value)) { $new_img = str_replace('<img', '<img alt="'.$post->post_title.'"', $images[0][$index]); } if(!preg_match('/title=/', $value)) { $new_img = str_replace('<img', '<img title="'.$post->post_title.'"', $images[0][$index]); } $content = str_replace($images[0][$index], $new_img, $content); } } return $content; } add_filter('the_content', 'add_alt_tags', 99999);