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

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

wordpress

只需将下面的代码添加到当前主题函数模板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. if ($res) {
  6. /*Clean up title: remove EOL's and excessive whitespace.*/
  7. $title = preg_replace('/s+/', ' ', $title_matches[1]);
  8. $title = trim($title);
  9. }
  10. preg_match_all('/<img (.*?)/>/', $buffer, $images);
  11. if(!is_null($images)) {
  12. foreach($images[1] as $index => $value) {
  13. preg_match('/alt="(.*?)"/', $value, $img);
  14. preg_match('/alt='(.*?)'/', $value, $img2);
  15. if(!is_null($images)) {
  16. if((!isset($img[1]) || $img[1] == '') || (!isset($img2[1]) || $img2[1] == '')) {
  17. $new_img = str_replace('<img', '<img alt="'.$title.'"', $images[0][$index]);
  18. $buffer = str_replace($images[0][$index], $new_img, $buffer);
  19. }
  20. }
  21. }
  22. }
  23. return $buffer;
  24. }
  25. function buffer_start() {
  26. ob_start();
  27. }
  28. function buffer_end() {
  29. echo callback(ob_get_clean());
  30. }
  31. add_action('wp', 'buffer_start', 0); add_action('wp_footer', 'buffer_end');

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

附其它方法:

  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);

给TA打赏
共{{data.count}}人
人已打赏
建站笔记

WordPress上传图片自动添加Alt和图像描述

2022-6-7 16:06:46

建站笔记

WordPress 只允许游客浏览指定分类的文章

2022-6-7 16:12:12

重要说明

本站资源大多来自网络,如有侵犯你的权益请联系管理员,发送邮件   68836010@qq.com  我们会第一时间进行审核删除。站内资源为网友个人学习或测试研究使用,未经原版权作者许可,禁止用于任何商业途径!请在下载24小时内删除!


如果遇到特殊找不到下载链接的文章,或者不能下载,或者解压失败,先不要忙。 有可能有事情或者在睡觉不能及时的回复您,QQ留言后, 请耐心等待即可! QQ:68836010  

0 条回复 A文章作者 M管理员
    暂无讨论,说说你的看法吧