Skip to content

Instantly share code, notes, and snippets.

@sabrina-zeidan
Created October 2, 2022 20:50
Show Gist options
  • Save sabrina-zeidan/11a4d3b227d24b0aa4f59731f0c73669 to your computer and use it in GitHub Desktop.
Save sabrina-zeidan/11a4d3b227d24b0aa4f59731f0c73669 to your computer and use it in GitHub Desktop.
Generate image alt from the post title -- for the first image in the post [WordPress]
// Generate image alt from the post title -- for the first image in the post
add_filter('the_content', 'add_alt_tags', 99999);
function add_alt_tags($content) {
global $post;
preg_match_all('/<img[^>]+>/i', $content, $images);
if(!is_null($images)) {
foreach($images[0] as $index => $value) {
//If no alt
// if(!preg_match('/alt=/', $value)) {
$new_img = str_replace('<img', '<img alt="'.get_the_title().'"', $images[0][$index]);
// var_dump($new_img);
$content = str_replace($images[0][$index], $new_img, $content);
//Just for the first image in post
break;
// }
}
}
return $content;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment