WordPress代码实现自动给图片链接加上title和alt标签

从SEO的策略角度看,需要将图片上加上ALT和TITLE,来提高搜素引擎的体验度。一般的WORDPRESS是没有这个功能,需要我们额外添加,这里直接用代码实现。

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');
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');

贴到 Functions.php 中实现。

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