【纯代码】wordpress 自动给内容页的图片添加alt属性+title属性
2023-01-14 20:25:06 1
大家好,对【纯代码】wordpress 自动给内容页的图片添加alt属性+title属性感兴趣的小伙伴,下面一起跟随草蛋来看看【纯代码】wordpress 自动给内容页的图片添加alt属性+title属性的介绍吧。
如果你觉得使用插件占用资源,下面用纯代码也是可以实现为图片自动添加alt标签,只需把下面代码添加WordPress主题 functions.php 文件即可。
在主题的 functions.php 文件,加入以下代码:
/**
* 【纯代码】wordpress 自动给内容页的图片添加alt属性+title属性
* @arrange (草蛋运维笔记) www.caocaoz.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;
$ju = '/title=/';
preg_match($ju,$tag,$match,PREG_OFFSET_CAPTURE);
if( count($match) < 1 )
$altURL = ' alt="'.$imgtitle.'第'.$j.'张" title="'.$imgtitle.'第'.$j.'张-'.$btitle.'" ';
$url = rtrim($url,'>');
$url .= $altURL.'>';
$imgalttitle = str_replace($tag,$url,$imgalttitle);
}
}
}
return $imgalttitle;
}
add_filter( 'the_content','image_alttitle');
* 【纯代码】wordpress 自动给内容页的图片添加alt属性+title属性
* @arrange (草蛋运维笔记) www.caocaoz.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;
$ju = '/title=/';
preg_match($ju,$tag,$match,PREG_OFFSET_CAPTURE);
if( count($match) < 1 )
$altURL = ' alt="'.$imgtitle.'第'.$j.'张" title="'.$imgtitle.'第'.$j.'张-'.$btitle.'" ';
$url = rtrim($url,'>');
$url .= $altURL.'>';
$imgalttitle = str_replace($tag,$url,$imgalttitle);
}
}
}
return $imgalttitle;
}
add_filter( 'the_content','image_alttitle');
添加完毕后,上传即可。这样在上传图片的时候就可以自动添加alt信息了。