WordPress将title标签作为WordPress文章图片的ALT

  • 酉灿
  • WordPress
  • Jul 23, 2021

WordPress站长在发表文章时,往往不注意给图片添加说明(ALT),导致大量文章中的图像缺少 ALT属性,不利于SEO。网上有很多自动给文章图片添加ALT属性的教程,这里转个国外的方法供参考。

只需将下面的代码添加到当前主题函数模板functions.php中即可。


 
  1. function callback($buffer) {
  2. /* modify buffer here, and then return the updated code*/
  3. $title='';
  4. $res = preg_match('/<title>(.*?)<\/title>/', $buffer, $title_matches);
  5.  
  6. if ($res) {
  7. /*Clean up title: remove EOL's and excessive whitespace.*/
  8. $title = preg_replace('/\s+/', ' ', $title_matches[1]);
  9. $title = trim($title);
  10. }
  11.  
  12. preg_match_all('/<img (.*?)\/>/', $buffer, $images);
  13. if(!is_null($images)) {
  14. foreach($images[1] as $index => $value) {
  15. preg_match('/alt="(.*?)"/', $value, $img);
  16. preg_match('/alt=\'(.*?)\'/', $value, $img2);
  17. if(!is_null($images)) {
  18. if((!isset($img[1]) || $img[1] == '') || (!isset($img2[1]) || $img2[1] == '')) {
  19. $new_img = str_replace('<img', '<img alt="'.$title.'"', $images[0][$index]);
  20. $buffer = str_replace($images[0][$index], $new_img, $buffer);
  21. }
  22. }
  23. }
  24. }
  25.  
  26. return $buffer;
  27. }
  28.  
  29. function buffer_start() { ob_start(); }
  30.  
  31. function buffer_end() { echo callback(ob_get_clean()); }
  32.  
  33. add_action('wp', 'buffer_start', 0);
  34. add_action('wp_footer', 'buffer_end');

代码中虽然加了缓冲区,但还是会降低效率,建议安装静态缓存插件。

代码源自:https://deano.me/2017/03/wordpress-fill-missingempty-alt-tags-with-title-for-seo

附其它方法:


 
  1. function img_alt($content) {
  2. global $post;
  3. preg_match_all('/<img (.*?)\/>/', $content, $images);
  4. if(!is_null($images)) {
  5. foreach($images[1] as $index => $value) {
  6. $new_img = str_replace('<img', '<img alt="'.get_the_title().'-'.get_bloginfo('name').'" title="'.get_the_title().'-'.get_bloginfo('name').'"', $images[0][$index]);
  7. $content = str_replace($images[0][$index], $new_img, $content);
  8. }
  9. }
  10. return $content;
  11. }
  12. add_filter('the_content', 'img_alt', 99999);

打赏