WordPress图片自动添加alt标签

如果你没有手动添加图片alt的习惯,那么我相信你是需要这个功能的,WordPress默认上传图片后图片名即为alt,像我这种习惯把图片命名成1234的亚历山大,于是就批量转换下alt标签吧。

梦飞扬采用的是文章标题加站点名称的方式,虽然如果一片文章内图片较多的话不太标准,但是我大部分文章都是1张配图,于是用这个没什么压力。

图片优化也是WordPress seo的一种重要手段,不需要额外做什么,只需要复制粘贴下就可以达到效果,何乐而不为?

/** Auto-Generate ALT tag for images */
function image_alt_tag($content){
    global $post;preg_match_all('/<img (.*?)/>/', $content, $images);
    if(!is_null($images)) {
        foreach($images[1] as $index => $value){
            if(!preg_match('/alt=/', $value)){
                $new_img = str_replace('<img', '<img alt="'.get_the_title().'"', $images[0][$index]);
                $content = str_replace($images[0][$index], $new_img, $content);}
        }
    }
    return $content;
}
add_filter('the_content', 'image_alt_tag', 99999);

将上面的代码直接加到functions.php中即可(已更新代码)。

展开评论