Skip to content

Instantly share code, notes, and snippets.

@mwordpress
Created February 8, 2017 15:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mwordpress/f0663b2fcf4d4b4eac2835ee914bcafc to your computer and use it in GitHub Desktop.
Save mwordpress/f0663b2fcf4d4b4eac2835ee914bcafc to your computer and use it in GitHub Desktop.
/*
* Add Missing Alt Tags To WordPress Images : advanced
* source : https://www.mwordpress.net/repair-alternative-alt-text-for-wordpress-images/
* Mwordpress.net - مجلة ووردبريس
*/
function fill_alt_tags($content){
global $post;
preg_match_all('/<img (.*?)\/>/', $content, $images);
$site_name = get_bloginfo('name');
$char_array = array();
$char_array[] = '-';
$char_array[] = '_';
if(!is_null($images)) {
foreach($images[1] as $index => $value) {
preg_match( '/src\s*=\s*([\'"])?((?(1).+?|[^\s>]+))(?(1)\1)/', $value, $source );
// ALT tag : Not Found
if(!preg_match('/alt=/', $value)) :
$file = preg_replace( '/\-*(\d+)x(\d+)\.(.*)$/', ' ', $source[2] );
$filename = pathinfo($file, PATHINFO_FILENAME);
$text = str_replace( '/\-*(\d+)x(\d+)\.(.*)$/', ' ', $filename );
$title = str_replace( $char_array, ' ', $text );
$new_img = str_replace('<img', '<img alt="'.$title.' - '.$site_name.'"', $images[0][$index]);
$content = str_replace($images[0][$index], $new_img, $content);
endif;
// ALT tag : Empty
if(preg_match('/alt=/', $value) and strpos($value, 'alt=""')) :
$file = preg_replace( '/\-*(\d+)x(\d+)\.(.*)$/', ' ', $source[2] );
$filename = pathinfo($file, PATHINFO_FILENAME);
$text = str_replace( '/\-*(\d+)x(\d+)\.(.*)$/', ' ', $filename );
$title = str_replace( $char_array, ' ', $text );
$new_img = str_replace('alt=""', 'alt="'.$title.' - '.$site_name.'"', $images[0][$index]);
$content = str_replace($images[0][$index], $new_img, $content);
endif;
}
return $content;
}
}
add_filter('the_content', 'fill_alt_tags');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment