将WordPress标题作为图片的ALT属性
发布时间:2024-01-05 栏目:建站知识
浏览:29
分类:wordpress教程
WordPress是一个流行的内容管理系统,它允许用户创建和管理网站。在WordPress中,标题是文章或页面的主要描述,它可以帮助搜索引擎了解网页的内容。此外,标题还可以作为图片的ALT属性,这对于SEO和可访问性都非常重要。ALT属性为无法显示图像的用户提供替代文本,例如使用屏幕阅读器的盲人用户。因此,在WordPress中,将标题作为图片的ALT属性是一个很好的做法,因为它可以提高网站的可访问性和搜索引擎排名。总之,WordPress提供了一个简单易用的方式来管理网站内容,并且可以通过设置标题作为图片的ALT属性来提高网站的可访问性和搜索引擎排名。
WordPress站长在发表文章时,往往不注意给图片添加说明(ALT),导致大量文章中的图像缺少 ALT属性,不利于SEO。网上有很多自动给文章图片添加ALT属性的教程,这里转个国外的方法供参考。
将title标签作为WordPress文章图片的ALT
只需将下面的代码添加到当前主题函数模板functions.php中即可。
1 | functioncallback( $buffer ){ /*modifybufferhere,andthenreturntheupdatedcode*/ $title = '' ; $res =preg_match( '/<title>(.*?)</title>/' , $buffer , $title_matches ); if ( $res ){ /*Cleanuptitle:removeEOL'sandexcessivewhitespace.*/ $title =preg_replace('/s+/ ',' ',$title_matches[1]);$title=trim($title);}preg_match_all(' /<img(.*?)/>/ ',$buffer,$images);if(!is_null($images)){foreach($images[1]as$index=>$value){preg_match(' /alt= "(.*?)" / ',$value,$img);preg_match(' /alt= '(.*?)' / ',$value,$img2);if(!is_null($images)){if((!isset($img[1])||$img[1]==' ')||(!isset($img2[1])||$img2[1]==' ')){$new_img=str_replace(' <img ',' <imgalt= "'.$title.'" ',$images[0][$index]);$buffer=str_replace($images[0][$index],$new_img,$buffer);}}}}return$buffer;}functionbuffer_start(){ob_start();}functionbuffer_end(){echocallback(ob_get_clean());}add_action(' wp ',' buffer_start ',0);add_action(' wp_footer ',' buffer_end'); |
代码中虽然加了缓冲区,但还是会降低效率,建议安装静态缓存插件。
附其它方法:
1 | functionimg_alt( $content ){ global $post ;preg_match_all( '/<img(.*?)/>/' , $content , $images ); if (! is_null ( $images )){ foreach ( $images [1] as $index => $value ){ $new_img = str_replace ( '<img' , '<imgalt="' .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' , 'img_alt' ,99999); |