很多站长在发表文章的时候,往往会忘记给WordPress文章图片添加说明,就会导致大量文章图像缺少alt属性,不利于我们SEO优化,为了方便我们可以使用title标签作为WordPress文章图片的alt属性。

只需将下面的代码添加到当前主题函数模板functions.php中即可。
function callback($buffer) {
/* modify buffer here, and then return the updated code*/
$title=”;
$res = preg_match(‘/<title>(.*?)<\/title>/’, $buffer, $title_matches);
if ($res) {
/*Clean up title: remove EOL’s and excessive whitespace.*/
$title = preg_replace(‘/\s+/’, ‘ ‘, $title_matches[1]);
$title = trim($title);
}
preg_match_all(‘/<img (.*?)\/>/’, $buffer, $images);
if(!is_null($images)) {
foreach($images[1] as $index => $value) {
preg_match(‘/’, $images[0][$index]);
$content = str_replace($images[0][$index], $new_img, $content);
}
}
return $content;
}
add_filter(‘the_content’, ‘img_alt’, 99999);