首页 » 资源 » 正文

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

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

1686150564 WordPress

//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');
声明: 如无特殊说明,本站文章均为原创,转载请注明出处:https://www.zjwiki.com/36192.html
收藏

相关推荐

发表评论

游客默认头像
    暂无评论
扫一扫二维码分享