I need to replace empty image alt in wordpress post content with image file name
I'm working on this function at the moment, please look at the comments:
// replace empty alt
function replace_empty_alt($content){
if (is_single()) {
// searching in content text like src="post_image.jpg" alt=""
$newAlt = preg_match_all('/[^\/]+(?=\.[^\/.]* alt="")/', $content, $matches);
// extracting image names
foreach ( $matches as $match) {
$imageNames = implode(',', $matches[0]);
}
// convert in array of ImageNames
$imageNamesNew = explode(',', $urls);
// foreach ImageName do a replace in content
foreach ((array) $imageNamesNew as $imageNameNew) {
$content = str_replace('alt=""', 'alt="'.$imageNameNew.'"', $content );
}
return $content;
}
}
add_filter('the_content', 'replace_empty_alt');
Basically what I need to do is to replace any empty alt in post content with exctrated image name. At the moment it partially works, but I get the same $imageNameNew for any empty alt.
Something like:
<img class="size-full aligncenter" src="image-name1.jpg" alt="image-name1" width="799" height="449">
<img class="size-full aligncenter" src="image-name2.jpg" alt="image-name1" width="799" height="449">
<img class="size-full aligncenter" src="image-name3.jpg" alt="image-name1" width="799" height="449">
While I want to get a correct replace like:
<img class="size-full aligncenter" src="image-name1.jpg" alt="image-name1" width="799" height="449">
<img class="size-full aligncenter" src="image-name2.jpg" alt="image-name2" width="799" height="449">
<img class="size-full aligncenter" src="image-name3.jpg" alt="image-name3" width="799" height="449">