当我们安装主题和插件时,都会向…

前天我们看到有个QQ群的网友在讨论,如何给网站中的图片自动添加图片的ALT和TITLE属性,因为在采集或者是编辑文章的时候确实图片太多的时候不会给图片添加这两个属性。如果我们采用的Wordpress肯定是有办法实现的,比如这里我们找到2个方法,可以实现自动在添加图片的时候加上属性。
1、方法A:添加ALT和TITLE
//文章图片自动添加alt和title属性(https://shop.mac163.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().'-'.get_bloginfo('name').'" title="'.get_the_title().'-'.get_bloginfo('name').'"', $images[0][$index]); $content = str_replace($images[0][$index], $new_img, $content);}} return $content; } add_filter('the_content', 'image_alt_tag', 99999);
2、方法B:添加ALT
//文章图片自动添加alt和title属性(https://shop.mac163.com/整理) function img_alt( $imgalt ){ global $post; $title = $post->post_title; $imgUrl = "<img\s[^>]*src=(\"??)([^\" >]*?)\[^>]*>"; 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');
这里将两处的代码选择其一,添加到当前WordPress主题或者子主题的Functions.php函数文件中就可以实现。

微信扫描二维码联系我们!
我们在微信上24小时期待你的声音
提供外贸路由器设备产品,轻松翻墙,解答:WP主题推荐,WP网站建设,Google SEO,百度SEO,专业服务器环境搭建等!
需要提供WordPress主题/插件的汉化服务可以随时联系我们!另外成品WordPress网站以及半成品WordPress网站建设,海外Google SEO优化托管服务,百度SEO优化托管服务,Centos/Debian服务器WP专用环境搭建,WP缓存服务器搭建,我们都是你的首选,拥有多年WP开源程序服务经验,我们一直在坚持客户体验,没有最好,只有更好!