图片的alt属性对网站SEO有重要的作用,我们在使用wordpress建站添加文章或页面时,很多时候会忘记添加图片的alt信息。对于有很多图片的网站,每张图片都要再去设置alt,也是一件很繁琐的事情。今天我们讲解一下给wordpress博客内容的图片自动添加图片的alt属性的方法。
实现的原理:判断上传的图片是否添加了alt属性,如果没有,会自动添加文章标题作为图片alt属性,以此来达到自动设置图片alt属性的功能。
切换到主题目录,打开functions.php文件,添加如下代码:
- //图片添加alt属性
- function image_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’,’image_alt’);
阅读全文
常见问题
下载地址失效了怎么版?
客服会第一时间检查下载地址,并发送到您的注册邮箱。如未及时处理可联系客服QQ或邮箱。
导入演示被中断了想重新导入怎么办?
https://themege.net/23822.html
不懂导入演示数据?无法一键导入演示数据?
https://themege.net/16186.html
原文链接:https://themege.net/3397.html,转载请注明出处。

评论0