WordPress文章图片自动添加alt和title信息

给WordPress文章内容中的图片添加alt和title信息,有助于搜索引擎的收录和识别。但是现在很多方法都失效了。插件又很臃肿。经过站长资料库老猫的亲自测试,只需要把以下代码添加到主题目录functions.php内即可实现。

//站长资料库文章图片自动添加alt和title信息 www.itszl.com
function image_alttitle( $imgalttitle ){
        global $post;
        $category = get_the_category();
        $flname=$category[0]->cat_name;
        $btitle = get_bloginfo();
        $imgtitle = $post->post_title;
        $imgUrl = "<img\s[^>]*src=(\"??)([^\" >]*?)\\1[^>]*>";
        if(preg_match_all("/$imgUrl/siU",$imgalttitle,$matches,PREG_SET_ORDER)){
                if( !empty($matches) ){
                        for ($i=0; $i < count($matches); $i++){
                                $tag = $url = $matches[$i][0];
                                $j=$i+1;
                                $judge = '/title=/';
                                preg_match($judge,$tag,$match,PREG_OFFSET_CAPTURE);
                                if( count($match) < 1 ) $altURL = ' alt="'.$imgtitle.' '.$flname.' 第'.$j.'张" title="'.$imgtitle.' '.$flname.' 第'.$j.'张-'.$btitle.'" '; $url = rtrim($url,'>');
                                $url .= $altURL.'>';
                                $imgalttitle = str_replace($tag,$url,$imgalttitle);
                        }
                }
        }
        return $imgalttitle;
}
add_filter( 'the_content','image_alttitle');

以上代码默认的 alt 属性为“文章标题 分类名称 第几张”,title 属性为“文章标题 分类名称 第几张-站点名称”。

0
分享到:

评论0

请先

没有账号? 忘记密码?