为什么需要灯箱?
很多时候,我们插入文章、页面中的图片因为尺寸或其他原因,图片是不太清晰的,尤其是截图。这样读者在观看的时候,体验会非常差。特别是有些教程中的图片,本来图片中的文字很小,如果图片还不是很清晰,教程的效果就会打折扣。实现图片点击放大功能,方法有很多种,有添加代码的,也有插件的。本着能不用插件就不用插件的原则,尽量还是用代码实现功能。
开工
方法1
在header.php中添加代码
注意:位置要在</header>之前
<link rel="stylesheet" href="https://jsd.onmicrosoft.cn/gh/fancyapps/fancybox@3.5.7/dist/jquery.fancybox.min.css" />

在footer.php中添加代码
注意:位置要在</body>之前
<script src="https://jsd.onmicrosoft.cn/gh/fancyapps/fancybox@3.5.7/dist/jquery.fancybox.min.js"></script>

在functions.php中添加代码
位置任意
注:你可能会在其它地方看到类似的代码。但是与他们不同的是,我的代码更他们相比,增加了对webp的兼容性:)
add_filter('the_content', 'fancybox');
function fancybox($content){
$pattern = array("/<img(.*?)src=('|\")([^>]*).(bmp|gif|jpeg|jpg|png|swf|webp)('|\")(.*?)>/i","/<a(.*?)href=('|\")([^>]*).(bmp|gif|jpeg|jpg|png|swf|webp)('|\")(.*?)>(.*?)<\/a>/i");
$replacement = array('<a$1href=$2$3.$4$5 data-fancybox="gallery"><img$1src=$2$3.$4$5$6></a>','<a$1href=$2$3.$4$5 data-fancybox="images"$6>$7</a>');
$content = preg_replace($pattern, $replacement, $content);
return $content;
}

方法2
首先,我们先随便选择一张图片

如图所示,点击“(-)”,然后点击“媒体文件”

大功告成
IN THE END
Comments 1 条评论
拿走了,我博客没灯箱被骂了好多次?