function add_missing_alt_from_media($content) {
global $post;
preg_match_all('/<img(.*?)src="([^"]+)"(.*?)>/', $content, $matches);
if (!empty($matches[0])) {
foreach ($matches[0] as $index => $img_tag) {
if (strpos($img_tag, 'alt=') === false || strpos($img_tag, 'alt=""') !== false) {
$image_url = $matches[2][$index];
$attachment_id = attachment_url_to_postid($image_url);
$alt_text = get_post_meta($attachment_id, '_wp_attachment_image_alt', true);
if ($alt_text) {
$new_img_tag = str_replace('<img', '<img alt="' . esc_attr($alt_text) . '"', $img_tag);
$content = str_replace($img_tag, $new_img_tag, $content);
}
}
}
}
return $content;
}
add_filter('the_content', 'add_missing_alt_from_media');