为文章图片自动添加alt和title属性(有完美判断)

网上有许多自动添加 alt 和 title 属性的代码,但是都并不完美,总有一些小问题。例如出现空白 alt 或 title 属性,或者出现重复 alt 或 title 属性。

下面是我自己在用的代码,能完美判断图片是否已有 alt 和 title 属性。如果有就保留,如果没有或者是空的就自动添加。代码如下,在主题的 functions.php 中添加即可:

function wpface_image_alt_title($content) {
	global $post;
	$alt_title = $post->post_title;
	preg_match_all('/<img(.*?)src=(\'|\")(.*?)\.(bmp|gif|jpeg|jpg|png)(\'|\")(.*?)>/i', $content, $matches);
	if($matches) {
		foreach($matches[0] as $val) {
			$place_content = $val;
			//先把空白 alt 和 title 属性清理掉
			$place_content = str_replace(' alt ', ' ', $place_content);
			$place_content = str_replace(' alt=""', '', $place_content);
			$place_content = str_replace(' title ', ' ', $place_content);
			$place_content = str_replace(' title=""', '', $place_content);
			//如果想覆盖原来的 alt 或 title 属性,就把下面两句的注释取消
			//$place_content = preg_replace('/ alt="(.*?)"/', '', $place_content);
			//$place_content = preg_replace('/ title="(.*?)"/', '', $place_content);
			//判断如果没有 alt 或 title 属性就用文章标题添加
			if(strpos($place_content,'alt=')===false) {
				$place_content = str_replace("/>", "", $place_content).' alt="'.$alt_title.'"/>';
			}
			if(strpos($place_content,'title=')===false) {
				$place_content = str_replace("/>", "", $place_content).' title="'.$alt_title.'"/>';
			}
			//替换 img 标签
			$content = str_replace($val, $place_content, $content);
		}
	}
	return $content;
}
add_filter('the_content','wpface_image_alt_title');

代码的思路是这样的:

  1. 通过正则匹配提取文章中所有图片标签,然后循环替换每条标签,并赋值到变量 $place_content
  2. 处理 $place_content,先把空白 alt 和 title 属性清理掉
  3. 判断是否存在 alt 或 title 属性,没有就添加
  4. 用处理后的 $place_content,替换文章中匹配到的 img 标签

Google