WordPress 文章内图片适配百度 mip-img 规范

张子凡 WordPress优化/百度MIP 2016-11-07 15:00:20 阅读(...) 评论(23)

百度 MIP 规范对原有网页 img 标签进行了重新的定义,需要使用 mip-img 用来支持在 mip 中增加的图片内容。对于将已有的页面改造引入 MIP 就必须将原有的所有图片使用 mip-img 标签,而在改造的时候,我们可以通过直接替换原有 img 标签,但是对于我们已经写入数据库的文章内容,直接输出的时候图片依然是 img,也不可能把数据库图片标签替换为 mip-img,所以最好的方式就是在输出内容的时候进行替换。

mip img

说了一堆凌乱的文字,不知道有人看得懂不,但是子凡的目的很明确,就是给大家提供一段可以在 WordPress 中,直接将文章中的图片直接替换并符合百度 MIP 中 mip-img 标签的规范,从而让你的 WordPress 文章页面图片内容也符合百度 MIP 规范。

下面直接上代码,直接将以下代码添加至当前 WordPress MIP 主题中的 functions.php 文件中:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
//WordPress 文章内图片适配百度 MIP 规范
//last update 2018/12/07
add_filter('the_content', 'fanly_mip_images');
function fanly_mip_images($content){
	preg_match_all('/<img (.*?)\>/', $content, $images);
	if(!is_null($images)) {
		foreach($images[1] as $index => $value){
			$mip_img = str_replace('<img', '<mip-img popup', $images[0][$index]);
			$mip_img = str_replace('>', '></mip-img>', $mip_img);
			//以下代码可根据需要修改/删除
			$mip_img = preg_replace('/(width|height)="\d*"\s/', '', $mip_img );//移除图片 width|height
			$mip_img = preg_replace('/ style=\".*?\"/', '',$mip_img);//移除图片 style
			$mip_img = preg_replace('/ class=\".*?\"/', '',$mip_img);//移除图片 class
			//以上代码可根据需要修改/删除
			$content = str_replace($images[0][$index], $mip_img, $content);
		}
	}
	return $content;
}

代码不算多,但是应该刚好能解决问题,同时子凡发布的免费版和收费版WordPress MIP 主题Fanly-MIP)也已经添加给功能,请大家放心使用即可。

WordPress 全站改造百度 MIP(mip-img)图片标签代码:https://zhangzifan.com/wordpress-mip-img-all.html

更多关于WordPress优化及疑问可以添加QQ群:255308000

除非注明,否则均为泪雪博客原创文章,禁止任何形式转载

本文链接:https://zhangzifan.com/wordpress-mip-img.html

留言评论

登录 后留言