WordPress内容页图片智能添加alt属性(自动添加文章标题作为图片alt属性)
1 | https://www.91wordpress.com/457.html |
切换到主题目录,打开functions.php文件,添加如下代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | 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'); |