One of the biggest SEO requirements is for images to have an ALT attribute for indexing and usability purposes, unfortunately when making posts most often ALT attributes are not set leading to lots and lots of posts with images missing their ALT attributes.
I wrote a small function that will capture the page before output and check all the images on the page, any images without an ALT or with a blank ALT will be modified so that the ALT tag is set to the page title, this not only removes the problem of missing ALT tags but will also hopefully boost your page title's authority and images on the page will have the same ALT description as the main page title.
It's easy to use just paste the code below into your functions.php file:
<?php function callback($buffer) { /* modify buffer here, and then return the updated code*/ $title=''; $res = preg_match('/<title>(.*?)<\/title>/', $buffer, $title_matches); if ($res) { /*Clean up title: remove EOL's and excessive whitespace.*/ $title = preg_replace('/\s+/', ' ', $title_matches[1]); $title = trim($title); } preg_match_all('/<img (.*?)\/>/', $buffer, $images); if(!is_null($images)) { foreach($images[1] as $index => $value) { preg_match('/alt="(.*?)"/', $value, $img); preg_match('/alt=\'(.*?)\'/', $value, $img2); if(!is_null($images)) { if((!isset($img[1]) || $img[1] == '') || (!isset($img2[1]) || $img2[1] == '')) { $new_img = str_replace('<img', '<img alt="'.$title.'"', $images[0][$index]); $buffer = str_replace($images[0][$index], $new_img, $buffer); } } } } return $buffer; } function buffer_start() { ob_start(); } function buffer_end() { echo callback(ob_get_clean()); } add_action('wp', 'buffer_start', 0); add_action('wp_footer', 'buffer_end'); ?>
Note: This may potentially slow the page a little on low spec servers, so having a good cache plugin is recommended.






So if you have the alt tag set in the editor this should ignor it and keep the new alt. But seems to override everything and insert the title on the image, anyway to only no alts and alt="" to have the title replaced?
I wonder how much it slows down the site. Speed optimization is one of the common tasks for wp sites so slowing down is a critical issue.
I've come to this page in search of some solution to control output of image tags so I can set alts and titles to them how I want. I thought I could find related hook or something. But buffering whole page looks too much excessive.
Also, check for empty $images on 20 line makes no sense. Perhaps you wanted to check $img and $img2.