wordpress代码实现图片自动添加ALT属性

我们在做wordpress主题的时候,会经常考虑到网站的SEO优化,比如给wordpress主题里的图片添加alt属性,但是一个个添加确实麻烦,如果可以自动添加那就方便的多了。

有的说有一个插件可以实现,但是我搜了那个插件,感觉和他说的不一样,也不知道是我没找对,另外,能不用插件我们还是少用插件的好,所以最后就找到了使用代码实现为wordpress主题自动添加atl属性的方法,将下面代码粘贴到您的主题function.php文件里就可以了。

如何给网站中的图片自动添加图片的ALT和TITLE属性,因为在采集或者是编辑文章的时候确实图片太多的时候不会给图片添加这两个属性。如果我们采用的Wordpress肯定是有办法实现的,比如这里老蒋找到2个方法,可以实现自动在添加图片的时候加上属性。

图片atl和title属性的区别

alt: 是w3c要求指定的属性,如果图片没有正常显示则会把alt设置的值显示在图片位置,并且利于SEO抓取图片信息
title: 是鼠标放在上面提示的文字

alt是必须加上的,至少百度搜索你的站点时会把alt当做图片的信息名字进行分类或者其它处理,title可以不加,如果你想要鼠标放在图片上时有提示信息就加上,不想用可以不加
再补一句,title不仅仅是图片img标签的属性也可以在其它标签中使用

1、方法A:添加ALT和TITLE

//文章图片自动添加alt和title属性(https://www.itbulu.com/wp-auto-alt.html整理)
function image_alt_tag($content){
global $post;preg_match_all(‘/<img (.*?)\/>/’, $content, $images);
if(!is_null($images)) {foreach($images[1] as $index => $value)
{$new_img = str_replace(‘<img’, ‘<img alt=”‘.get_the_title().’-‘.get_bloginfo(‘name’).'” title=”‘.get_the_title().’-‘.get_bloginfo(‘name’).'”‘, $images[0][$index]);
$content = str_replace($images[0][$index], $new_img, $content);}}
return $content;
}
add_filter(‘the_content’, ‘image_alt_tag’, 99999);

2、方法B:添加ALT

//文章图片自动添加alt和title属性(https://www.itbulu.com/wp-auto-alt.html整理)
function img_alt( $imgalt ){
global $post;
$title = $post->post_title;
$imgUrl = “<img\s[^>]*src=(\”??)([^\” >]*?)\\1[^>]*>”;
if(preg_match_all(“/$imgUrl/siU”,$imgalt,$matches,PREG_SET_ORDER)){
if( !empty($matches) ){
for ($i=0; $i < count($matches); $i++){
$tag = $url = $matches[$i][0];
$judge = ‘/alt=/’;
preg_match($judge,$tag,$match,PREG_OFFSET_CAPTURE);
if( count($match) < 1 )
$altURL = ‘ alt=”‘.$title.'” ‘;
$url = rtrim($url,’>’);
$url .= $altURL.’>’;
$imgalt = str_replace($tag,$url,$imgalt);
}
}
}
return $imgalt;
}

add_filter( ‘the_content’,’img_alt’);

这里将两处的代码选择其一,添加到当前主题的Functions.php文件中就可以实现。

THE END