WordPress站长在发表文章时,往往不注意给图片添加说明(ALT),导致大量文章中的图像缺少 ALT属性,不利于SEO。网上有很多自动给文章图片添加ALT属性的教程,这里转个国外的方法供参考。
将title标签作为WordPress文章图片的ALT
只需将下面的代码添加到当前主题函数模板functions.php中即可。
function callback($buffer) { /* modify buffer here, and then return the updated code*/ $title=''; $res = preg_match('/<title>(.*?)<\/title>/', $buffer, $title_matches); if ($res) { /*Clean up title: remove EOL's and excessive whitespace.*/ $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', '<img alt="'.$title.'"', $images[0][$index]); $buffer = str_replace($images[0][$index], $new_img, $buffer); } } } } return $buffer; } function buffer_start() { ob_start(); } function buffer_end() { echo callback(ob_get_clean()); } add_action('wp', 'buffer_start', 0); add_action('wp_footer', 'buffer_end');
代码中虽然加了缓冲区,但还是会降低效率,建议安装静态缓存插件。
附其它方法:
function img_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', '<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', 'img_alt', 99999);
本站所有资源来源于用户上传和网络,如有侵权请邮件联系站长!邮箱:yangbinvap@qq.com分享目的仅供大家学习和交流,您必须在下载后24小时内删除!不得使用于非法商业用途,不得违反国家法律。否则后果自负!本站提供的源码、模板、插件等等其他资源,都不包含技术服务请大家谅解!如有链接无法下载、失效或广告,请联系管理员处理!本站资源售价只是赞助,收取费用仅维持本站的日常运营所需!如遇到加密压缩包,请使用WINRAR解压,如遇到无法解压的请联系管理员! 精力有限,不少源码未能详细测试(解密),不能分辨部分源码是病毒还是误报,所以没有进行任何修改,大家使用前请进行甄别。