WordPress图片的SEO自动加上 title 和 alt 标签
网站 seo 要求每张图片都要有 alt 属性,手动去改显然不显示,因此写了个函数,将下面的代码加入到主题的 functions.php 文件中即可。
//图片img标签添加alt,title属性
function imagesalt($content) {
global $post;
$pattern ="/<img(.*?)src=('|\")(.*?).(bmp|gif|jpeg|jpg|png)('|\")(.*?)>/i";
$replacement = '<img$1src=$2$3.$4$5 alt="'.$post->post_title.'" title="'.$post->post_title.'"$6>';
$content = preg_replace($pattern, $replacement, $content);
return $content;
}
add_filter('the_content', 'imagesalt');
//图片A标签添加alt,title属性
function aimagesalt($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;
}
add_filter('the_content', 'aimagesalt');