WordPress自动为img图片添加alt属性
admin 阅读:142 2024-03-01
网站 seo 要求每张图片都要有 alt 属性,手动去改显然不显示,因此写了个函数,将下面的代码加入到主题的 functions.php 文件中即可。
//Wordpress判断并自动添加图片ALT属性
function image_alt($imgalt) {
global $post;
$title = $post->post_title;
$imgUrl = "/<imgs*?.+?[^>]>/si";
$isMatch=preg_match_all($imgUrl,$imgalt,$matches,PREG_SET_ORDER);
if($isMatch) {
if(!empty($matches) ) {
for ($i=0; $i < count($matches); $i++) {
$tag = $url = $matches[$i][0];
$tag=preg_replace('/alt="s*"/','',$tag);
$judge = '/alt=/';
$isMatched=preg_match($judge,$tag,$match,PREG_OFFSET_CAPTURE);
if($isMatched) {
continue;
}
$tag=preg_replace('/<img/','<img alt="'.$title.'-第'.$i.'张图片"',$tag);
$imgalt =str_replace($url,$tag,$imgalt);
}
}
}
return $imgalt;
}
add_filter('the_content', 'image_alt');声明
1、部分文章来源于网络,仅作为参考。 2、如果网站中图片和文字侵犯了您的版权,请联系1943759704@qq.com处理!



