SEO优化
我们更专业

WordPresswp怎么给图片自动添加alt和title属性免插件

WordPresswp怎么给图片自动添加alt和title属性。因为在我们在上传的时候一忙光把图片的属性给忘了设置和替换。但是本身图片也不会给图片添加这两个属性。如果我们采用的Wordpress肯定是有办法实现的。新起点博客来网上搜集了两种方法,免插件可以可以实现自动在添加图片的时候加上属性(亲测有效)。alt属性为文章标题,方法如下:

1、添加alt和title方法

//文章图片自动添加alt和title属性www.seoccc.com)
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().'" title="'.get_the_title().'"', $images[0][$index]);
$content = str_replace($images[0][$index], $new_img, $content);}}
return $content;
}
add_filter('the_content', 'image_alt_tag', 99999);

2、添加alt方法

//文章图片自动添加alt和title属性www.seoccc.com整理)
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');

将以上代码选择一种方法添加到主题中的funcations.php文件即可实现

版权声明:本站文章及图片来自互联网及其他公众平台,版权归原作者,如有侵权请联系我们删除!
本文链接:https://www.seoccc.com/wordpress/224.html