WordPress内容图片自动加上ALT和TITLE标签的两个方法

2021-11-2807:37:20网站建设与开发Comments1,452 views字数 1701阅读模式

SEO角度我们需要给文章中的图片添加ALT和TITLE标签的。有些时候我们是不是会忘记?这里我们可以实现自动添加标签。在这篇文章中,老蒋用代码实现WordPress内容图片自动加上TITLE和ALT标签办法。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/cms/22717.html

WordPress内容图片自动加上ALT和TITLE标签的两个方法文章源自菜鸟学院-https://www.cainiaoxueyuan.com/cms/22717.html

1、方法一文章源自菜鸟学院-https://www.cainiaoxueyuan.com/cms/22717.html

function image_alttitle( $imgalttitle ){
global $post;
$category = get_the_category();
$flname=$category[0]->cat_name;
$btitle = get_bloginfo();
$imgtitle = $post->post_title;
$imgUrl = "<img\s[^>]*src=(\"??)([^\" >]*?)\\1[^>]*>";
if(preg_match_all("/$imgUrl/siU",$imgalttitle,$matches,PREG_SET_ORDER)){
if( !empty($matches) ){
for ($i=0; $i < count($matches); $i++){
$tag = $url = $matches[$i][0];
$j=$i+1;
$judge = '/title=/';
preg_match($judge,$tag,$match,PREG_OFFSET_CAPTURE);
if( count($match) < 1 )
$altURL = ' alt="'.$imgtitle.' '.$flname.' 第'.$j.'张" title="'.$imgtitle.' '.$flname.' 第'.$j.'张-'.$btitle.'" ';
$url = rtrim($url,'>');
$url .= $altURL.'>';
$imgalttitle = str_replace($tag,$url,$imgalttitle);
}
}
}
return $imgalttitle;
}
add_filter( 'the_content','image_alttitle');

2、方法二文章源自菜鸟学院-https://www.cainiaoxueyuan.com/cms/22717.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').'"', $images[0][$index]);
$content = str_replace($images[0][$index], $new_img, $content);}}
return $content;
}
add_filter('the_content', 'image_alt_tag', 99999);

同时,我们也可以使用Image Automatic Alt Text and Caption插件。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/cms/22717.html

备注ALT和TITLE属性:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/cms/22717.html

Alt属性文章源自菜鸟学院-https://www.cainiaoxueyuan.com/cms/22717.html

alt属性是图片的描述,即图片内容的文本介绍。当图片因为一些意外情况出现加载不出来的情况下,img的alt属性这时候就会显示在未加载出来的图片填充范围内,方便用户在浏览网页的时候知道这一段区域内的图片表达的是什么。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/cms/22717.html

alt属性相当于一张图片的内容介绍,当搜索引擎在访问网站的时候索引这张图片时通常第一时间获取的则是这张图片的内容介绍,从而记录这张图片表达的是什么。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/cms/22717.html

Title属性文章源自菜鸟学院-https://www.cainiaoxueyuan.com/cms/22717.html

title属性则是标题,如果放在img标签当中则是表示图片的标题。以前在ie浏览器时代中,有那么一段时间一直使用的是alt属性为鼠标停留图片时展现出来的内容,而现今在Chrome浏览器时代,已经全部使用title替代鼠标悬浮图片时展现的内容了。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/cms/22717.html

对于现在而言alt属性和title属性区分的已经不是那么明显,不过国内的搜索引擎,还没有发展到使用title替代alt属性的地步,所以相对来说alt属性对于图片而言还是重要一些。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/cms/22717.html

  • 本站内容整理自互联网,仅提供信息存储空间服务,以方便学习之用。如对文章、图片、字体等版权有疑问,请在下方留言,管理员看到后,将第一时间进行处理。
  • 转载请务必保留本文链接:https://www.cainiaoxueyuan.com/cms/22717.html

Comment

匿名网友 填写信息

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定