共計 1080 個字符,預計需要花費 3 分鐘才能閱讀完成。
使用 wordpress 建站時,有些主題沒有很好優化網站文章頁圖片的 Alt 描述,對其進行優化通常采取兩種策略,使用插件或者使用代碼,當然,對于 SEO 站長而言,通常更傾向于代碼來解決問題。下面隨橘子君一起來了解一下吧。
wordpress 文章頁圖片自動加描述的代碼:
// 文章圖片自動添加 alt 和 title 屬性
function image_alt_tag($content){global $post;preg_match_all('/<img (.*?)/>/', $content, $images);
if(!is_null($images)) {foreach($images[1] as $index => $value)
{$new_img = str_replace('<img', '<img alt="'.get_the_title().'-'.get_bloginfo('name').'"title="'.get_the_title().'-'.get_bloginfo('name').'"', $images[0][$index]);
$content = str_replace($images[0][$index], $new_img, $content);}}
return $content;
}
add_filter('the_content', 'image_alt_tag', 99999);
直接將上面的代碼添加到即可,文章頁的圖片圖片不僅添加了 Alt 描述,還添加了 title 標簽,當然,若你不想展現 title 標簽,以及 Alt 標簽描述后綴的主標題,可以將它們刪除,以下便是修改后的代碼:
// 文章圖片自動添加 alt 屬性
function image_alt_tag($content){global $post;preg_match_all('/<img (.*?)/>/', $content, $images);
if(!is_null($images)) {foreach($images[1] as $index => $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);
此種方法比較友好,對于之前發過的舊文章也同樣具有效果。
正文完