1 WordPress为全站用户头像图片增加alt属性,优化seo
今天在Bing Webmasters中查看网站的信息时,在SEO报告中出现了img未定义alt属性的问题。
经过对网站问题的排查,发现文章中的所有图片都是有alt属性的,就是文章后面的评论中每个用户的头像是没有alt属性的。之前是在代码中为文章内容中的图片都自动添加了alt属性,代码如下
function auto_image_alt($imgalt) {
    global $post;
    $title = $post->post_title;
    $imgUrl = "/<img\s*?.+?[^>]>/si";
    $isMatch=preg_match_all($imgUrl,$imgalt,$matches,PREG_SET_ORDER);
    if($isMatch) {
        if(!empty($matches) ) {
            for ($i=0; $i < count($matches); $i++) {
                $tag = $url = $matches[$i][0];
                $tag=preg_replace('/alt="\s*"/','',$tag);
                $judge = '/alt=/';
                $isMatched=preg_match($judge,$tag,$match,PREG_OFFSET_CAPTURE);
                if($isMatched) {
                   continue;
                }
                $tag=preg_replace('/<img/','<img alt="'.$title.'-第'.$i.'张图片"',$tag);
                $imgalt =str_replace($url,$tag,$imgalt);
            }
        }
    }
    return $imgalt;
}
add_filter('the_content', 'auto_image_alt');
不过上述代码不能为文章后面的评论列表的用户头像加上alt属性,经过查看get_avatar函数,如果要为全站的用户头像图片增加alt属性,可以在function.php中增加以下代码
add_filter( 'get_avatar', 'add_avatar_alt', 10, 5 );
function add_avatar_alt($avatar, $id_or_email, $size, $default, $alt){
    if( !empty($alt)) 
        return $avatar;
    $alt = get_bloginfo("name").'-'.get_comment_author()."头像";
    $before = strpos( $avatar, "alt='" );
    $after = strpos( $avatar, "'", $before );
    if( $before === false || $after === false )
        return $avatar;
    $alt = esc_attr( $alt );
    return substr( $avatar, 0, $before ) . "alt='$alt" . substr( $avatar, $after + strlen( "'" ) );
}
本文作者:StubbornHuang
版权声明:本文为站长原创文章,如果转载请注明原文链接!
原文标题:WordPress – 为全站用户头像图片增加alt属性,优化seo
原文链接:https://www.stubbornhuang.com/2856/
发布于:2023年10月19日 9:53:49
修改于:2023年10月19日 9:53:49
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。
 
				 
 
 
																					 
														
						 
														
						
评论
70