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('/(.*?) /', $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('//', $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('代码中虽然提了缓冲区,但还是会减少效率,建议安装静态内存插件。
附其它方法:
function img_alt($content) { global $post; preg_match_all('//', $content, $images); if(!is_null($images)) { foreach($images[1] as $index => $value) { $new_img = str_replace('