将title标签作为WordPress文章图片的ALT

WordPress2766阅读模式

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');

代码中虽然加了缓冲区,但还是会降低效率,建议安装静态缓存插件。

代码源自:https://deano.me/2017/03/wordpress-fill-missingempty-alt-tags-with-title-for-seo

附其它方法:

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);

本站文章大部分始于原创,用于个人学习记录,可能对您有所帮助,仅供参考!

weinxin
我的微信
版权声明
本站原创文章转载请注明文章出处及链接,谢谢合作!
 
知更鸟
  • functions.php
  • WordPress
评论  2  访客  2
    • Yan
      Yan 6

      新版wp编辑文章时,作者都直接在图片下方标记figcaptioin了,title和alt平时都懒得写。请问有没有直接调取图片figcaption并加入title和alt的方法。

      • Yan
        Yan 6

        已解决。

      匿名

      发表评论

      匿名网友
      :?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

      拖动滑块以完成验证