这个网站快2年了,到今天为止依然是图片贴死的方式。今天不用插件直接用代码解决这个问题。其实我的主题默认的编辑器里就有这个功能,但我一直不知道也就没有勾选。这次的代码,可以直接把过往的图片全都加上这个效果,省我不少力气。

代码写在哪里?
写在主题的function.php,最下方即可。
在既定位置插入代码
/**
* 自动为文章内图片添加灯箱链接属性
*/
add_filter('the_content', 'auto_add_lightbox_attributes');
function auto_add_lightbox_attributes($content) {
// 匹配没有被 <a> 标签包裹的 <img> 标签
$pattern = "/<img([^>]*?)src=['\"]([^\"^']+)['\"]([^>]*?)>/i";
// 自动套上链接,并指向原图 src,增加灯箱属性
$replacement = '<a href="$2" data-featherlight="image"><img$1src="$2"$3></a>';
$content = preg_replace($pattern, $replacement, $content);
return $content;
}
/**
* 引入 Featherlight 轻量灯箱 CSS 和 JS
*/
add_action('wp_enqueue_scripts', 'enqueue_lightbox_scripts');
function enqueue_lightbox_scripts() {
// 引入 CSS 样式
wp_enqueue_style('featherlight-css', 'https://cdn.jsdelivr.net/npm/featherlight@1.7.14/release/featherlight.min.css');
// 引入 JS 脚本(依赖 jQuery,WordPress 默认已内置)
wp_enqueue_script('featherlight-js', 'https://cdn.jsdelivr.net/npm/featherlight@1.7.14/release/featherlight.min.js', array('jquery'), null, true);
}刷新一下页面,完成。
换主题的话一定记得把代码带过去。