WordPress自动给内容图片添加 Title 和 Alt标签

从SEO角度考虑,我们内容中的图片是需要加上 Title 和 Alt 标签的。但是,一般的主题和程序是不会自动帮助我们添加,我们需要自己手工添加。如果你忘记或者不添加,那是否有自动添加的方法呢?

//自动添加alt和title
add_filter('the_content', 'imagesalt');
function imagesalt($content) {
       global $post;
       $pattern ="/<a(.*?)href=('|\")(.*?).(bmp|gif|jpeg|jpg|png)('|\")(.*?)>/i";
       $replacement = '<a$1href=$2$3.$4$5 alt="'.$post->post_title.'" title="'.$post->post_title.'"$6>';
       $content = preg_replace($pattern, $replacement, $content);
       return $content;
}

将代码添加到 Functions.php 中,可以会不需要手工添加,会将标题添加作为图片的 TITLE和ALT标签。

4.8/5 - (5 votes)
© 版权声明
THE END
喜欢就支持一下吧
点赞14 分享