WordPress 网站在做SEO时,给图片加上合适的title与是非常重要的,这是在做站内SEO优化的重要一部分。
将下方的代码,复制到主题的functions.php文件中,保存,重启PHP即可。
function miaoroom_auto_title_alt($content)
{
global $post;
$category = get_the_category();
$flname = $category[0]->cat_name;
$btitle = get_bloginfo();
$imgtitle = $post->post_title;
$imgUrl = "<imgs[^>]*src=("??)([^" >]*?)1[^>]*>";
if (preg_match_all("/$imgUrl/siU", $content, $matches, PREG_SET_ORDER)) {
if (empty($matches)) {
return $content;
}
for ($i = 0; $i < count($matches); $i++) {
preg_match_all('/(src|alt|title)=("[^"]*")/i', $matches[$i][0], $matched);
if ($matched) {
$j = $i + 1;
$attribute = '="' . $imgtitle . ' ' . $flname . ' 第' . $j . '张"';
$newTag = $matches[$i][0];
foreach ($matched[1] as $k => $v) {
if ($v != 'src') {
$newTag = str_replace($matched[0][$k], $matched[1][$k] . $attribute, $newTag);
}
}
if (!in_array('title', $matched[1])) {
$start = strpos($matches[$i][0], 'src');
$newTag = substr_replace($newTag, 'title' . $attribute, $start, 0);
}
if (!in_array('alt', $matched[1])) {
$start = strpos($matches[$i][0], 'src');
$newTag = substr_replace($newTag, 'alt' . $attribute, $start, 0);
}
$content = str_replace($matches[$i][0], $newTag, $content);
}
}
}
return $content;
}
add_filter('the_content', 'miaoroom_auto_title_alt');