WordPress:自动为img图片添加alt属性

网站 seo 要求每张图片都要有 alt 属性,手动去改显然不现实,因此写了个函数,将下面的代码加入到主题的 functions.php 文件中即可。

//Wordpress判断并自动添加图片ALT属性
function image_alt($imgalt) {
    global $post;
    $title = $post->post_title;
    $imgUrl = "/<img\s*?.+?[^>]>/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');

【AD】DMIT美国洛杉矶Pro VPS套餐,$14.9/月起,1G-10Gbps带宽/CN2 GIA线路/有高防GIA可选
【AD】美国洛杉矶CN2 VPS/香港CN2 VPS/日本CN2 VPS推荐,延迟低、稳定性高、免费备份_搬瓦工vps