向图像添加缺少的Alt标记-WordPress内容筛选器

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了向图像添加缺少的Alt标记-WordPress内容筛选器相关的知识,希望对你有一定的参考价值。

Simple function - just place it in your theme's functions.php file, save, and you're good to go. If an image in your content is missing the alt tag, it adds that posts title as the alt tag for the image.

It's been recommended to me that I shouldn't be using regex to parse html, and I made an attempt to do this with DOMDocument, but it wasn't working out to well. If there are any DOMDocument ninjas around, maybe they could slice this up a little easier.

Update: removed the "(.*?)" from the '/alt=/' regex, just in case an image had an alt already defined, but using single quotes instead.
  1. function add_alt_tags($content)
  2. {
  3. global $post;
  4. preg_match_all('/<img (.*?)/>/', $content, $images);
  5. if(!is_null($images))
  6. {
  7. foreach($images[1] as $index => $value)
  8. {
  9. if(!preg_match('/alt=/', $value))
  10. {
  11. $new_img = str_replace('<img', '<img alt="'.get_the_title().'"', $images[0][$index]);
  12. $content = str_replace($images[0][$index], $new_img, $content);
  13. }
  14. }
  15. }
  16. return $content;
  17. }
  18. add_filter('the_content', 'add_alt_tags', 99999);

以上是关于向图像添加缺少的Alt标记-WordPress内容筛选器的主要内容,如果未能解决你的问题,请参考以下文章

将alt-tag添加到滑块 - Wordpress

php 自动将Alt标签添加到WordPress图像上传

php 一个示例插件,显示如何向WordPress添加自定义查询变量,重写标记和重写规则

向WordPress添加自定义图像大小

从 Wordpress 媒体库中获取单个特定图像

在 Wordpress 中并排添加两个标题图像