WordPress添加文章时上传的图片怎么设置自动添加标题为alt属性,今天小编为大家分享一个方法,只需要两步即可实现,快来看看吧!
根据目录找到主题/wp-content/themes/******/functions.php文件,添加如下代码↓
/** *自动为wordpress文章图片添加alt属性和title属性 */ 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; $judge = '/title=/'; preg_match($judge,$tag,$match,PREG_OFFSET_CAPTURE); if( count($match) < 1 ) $altURL = ' alt="'.$imgtitle.' '.$flname.' 第'.$j.'张-'.$btitle.'" title="'.$imgtitle.' '.$flname.' 第'.$j.'张-'.$btitle.'" '; $url = rtrim($url.''); $url .= $altURL.''; $imgalttitle = str_replace($tag,$url,$imgalttitle); } } } return $imgalttitle; } add_filter( 'the_content','image_alttitle'); |
希望可以帮助到您!