当前位置: 主机百科 » 资源 » 正文

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

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

1686150564 WordPress

//Wordpress判断并自动添加图片ALT属性
function image_alt($imgalt) {
    global $post;
    $title = $post->post_title;
    $imgUrl = "/]>/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('/'.$title.'-第'.$i.'张图片
未经允许不得转载:主机百科 » WordPress:自动为img图片添加alt属性

相关文章