WordPress将title标签作为文章图片的alt属性

追格官方小助手/ 2022年12月24日/ WordPress/ 浏览 1001

WordPress文章中的图片添加alt属性,很多时候都是因为SEO,但很多人包括小编在内,很多时候也是不会去添加的。


相关阅读:
1、为WordPress文章图片自动添加alt与title属性
2、WordPress图片怎么自动添加alt和title属性


今天追格小编教你如何将title标签作为文章图片的alt属性。


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


上面代码添加到当前WordPress模板的functions.php文件中即可。


需要注意的是,上面代码中虽有缓冲区代码,可能还会降低效率,建议安装静态缓存插件。

发表评论

暂无评论,抢个沙发...

客服 工单