前天老蒋看到有个QQ群的网友在讨论,如何给网站中的图片自动添加图片的ALT和TITLE属性,因为在采集或者是编辑文章的时候确实图片太多的时候不会给图片添加这两个属性。如果我们采用的Wordpress肯定是有办法实现的,比如这里老蒋找到2个方法,可以实现自动在添加图片的时候加上属性。

1、方法A:添加ALT和TITLE

> //文章图片自动添加alt和title属性(https://www.itbulu.com/wp-auto-alt.html整理)
> 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);

2、方法B:添加ALT

> //文章图片自动添加alt和title属性(https://www.itbulu.com/wp-auto-alt.html整理)
> function img_alt( $imgalt ){
> global $post;
> $title = $post->post_title;
> $imgUrl = "<img\s[^>]src=(\"??)([^\" >]?)\\1[^>]*>";
> if(preg_match_all("/$imgUrl/siU",$imgalt,$matches,PREG_SET_ORDER)){
> if( !empty($matches) ){
> for ($i=0; $i < count($matches); $i++){
> $tag = $url = $matches[$i][0];
> $judge = '/alt=/';
> preg_match($judge,$tag,$match,PREG_OFFSET_CAPTURE);
> if( count($match) < 1 )
> $altURL = ' alt="'.$title.'" ';
> $url = rtrim($url,'>');
> $url .= $altURL.'>';
> $imgalt = str_replace($tag,$url,$imgalt);
> }
> }
> }
> return $imgalt;
> }
> add_filter( 'the_content','img_alt');

这里将两处的代码选择其一,添加到当前主题的Functions.php文件中就可以实现。