为WordPress文章图片自动添加alt与title属性

追格官方小助手/ 2022年07月22日/ WordPress/ 浏览 1132

为WordPress文章图片自动添加alt与title属性,判断图片是否已有 alt 和 title 属性,若有即保留原有信息,若无即自动添加。


我们只需将以下代码放到当前WordPress主题 functions.php 中即可。


function zhuige_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;
			$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);
			//$place_content = preg_replace('/ alt="(.*?)"/', '', $place_content);
			//$place_content = preg_replace('/ title="(.*?)"/', '', $place_content);
			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.'"/>';
			}
			$content = str_replace($val, $place_content, $content);
		}
	}
	return $content;
}
add_filter('the_content','zhuige_image_alt_title');

发表评论

暂无评论,抢个沙发...

客服 工单