网站建设中使用图文并茂的文章常常会更能够吸引用户,这时候我们在进行网站优化中不可避免要给图片添加一些alt和title属性,能够给访客更好的用户体验,也更利于SEO优化。一般WordPress主题是不具备自动添加标签功能,那么WordPress如何实现图片自动添加alt和title标签属性?
请将下面的代码复制粘贴到functions.php文件里面。
方法一:
/** 文章图片自动添加ALT和TITLE */
function image_alt_title($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_title\’, 99999);
方法二:
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\’);
以上代码默认的 alt 属性为“文章标题 分类名称 第几张”,title 属性为“文章标题 分类名称 第几张-站点名称”。
本文来源于 网络,由本站搜集发布,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系本站核实处理。如需转载,请注明文章来源。