两个方法实现WordPress自动给图片添加alt和title属性
ssr
撰写于 2022年 02月 26 日

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


//文章图片自动添加alt和title属性(https://www.itbulu.com/wp-auto-alt.html整理)
function image_alt_tag($content){<br> global $post;preg_match_all('/ https://www.itbulu.com/wp-auto-alt.html整理)
function img_alt( $imgalt ){<br> global $post;
$title = $post->post_title;
$imgUrl = "<img\s[^>]*src=(\"??)([^\" >]*?)\\1[^>]*>";<br> if(preg_match_all("/$imgUrl/siU",$imgalt,$matches,PREG_SET_ORDER)){
if( !empty($matches) ){<br> for ($i=0; $i < count($matches); $i++){<br> $tag = $url = $matches[$i][0];<br> $judge = '/alt=/';
preg_match($judge,$tag,$match,PREG_OFFSET_CAPTURE);<br> 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文件中就可以实现。

两个方法实现WordPress自动给图片添加alt和title属性

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


//文章图片自动添加alt和title属性(https://www.itbulu.com/wp-auto-alt.html整理)
function image_alt_tag($content){<br> global $post;preg_match_all('/ https://www.itbulu.com/wp-auto-alt.html整理)
function img_alt( $imgalt ){<br> global $post;
$title = $post->post_title;
$imgUrl = "<img\s[^>]*src=(\"??)([^\" >]*?)\\1[^>]*>";<br> if(preg_match_all("/$imgUrl/siU",$imgalt,$matches,PREG_SET_ORDER)){
if( !empty($matches) ){<br> for ($i=0; $i < count($matches); $i++){<br> $tag = $url = $matches[$i][0];<br> $judge = '/alt=/';
preg_match($judge,$tag,$match,PREG_OFFSET_CAPTURE);<br> 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文件中就可以实现。

赞 (0)

猜您想看

评论区(暂无评论)

这里空空如也,快来评论吧~

我要评论