wordpress自动给文章页图片添加Alt描述的方法

橘子网 4,713

使用wordpress建站时,有些主题没有很好优化网站文章页图片的Alt描述,对其进行优化通常采取两种策略,使用插件或者使用代码,当然,对于SEO站长而言,通常更倾向于代码来解决问题。下面随橘子君一起来了解一下吧。

wordpress自动给文章页图片添加Alt描述的方法

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

此种方法比较友好,对于之前发过的旧文章也同样具有效果。

 

上一篇:

下一篇:

相关阅读

分享