添加微信,1 对 1 沟通方案与报价
专业wordpress外贸建站、维护
继续分享wordpress建站教程。之前的一个wordpress外贸建站项目中,文章的图库需要添加一个灯箱弹出放大效果,这可以使用wordpress自带的功能,但是有个问题,如果图库图片数量多,需要一张张添加灯箱效果,效率太低。
为了提高效率,可以使用下面的代码:
/** * WP原生图库自动灯箱,无需后台手动设置图片链接 */ add_action( 'wp_enqueue_scripts', function() { if ( ! is_singular() ) return; wp_enqueue_style( 'baguettebox-css', 'https://cdn.jsdelivr.net/npm/baguettebox.js@1.11.1/dist/baguetteBox.min.css', [], '1.11.1' ); wp_enqueue_script( 'baguettebox-js', 'https://cdn.jsdelivr.net/npm/baguettebox.js@1.11.1/dist/baguetteBox.min.js', [], '1.11.1', true ); $init_js = <<<JS document.addEventListener('DOMContentLoaded', function(){ document.querySelectorAll('.wp-block-gallery, .gallery').forEach(function(galleryEl){ const imgs = galleryEl.querySelectorAll('img[class*="wp-image-"]'); imgs.forEach(function(img){ // 已经被a标题包裹则跳过,避免重复嵌套 if(img.parentElement.tagName === 'A') return; const imgIdMatch = img.className.match(/wp-image-(\d+)/); if(!imgIdMatch) return; const attId = parseInt(imgIdMatch[1]); const fullUrl = img.dataset.full || img.src; const a = document.createElement('a'); a.href = fullUrl; a.dataset.attachmentId = attId; img.parentNode.insertBefore(a, img); a.appendChild(img); }); // 初始化当前图库分组灯箱 baguetteBox.run(galleryEl, { captions: function(el){ return el.querySelector('img').alt || ''; } }); }); }); JS; wp_add_inline_script('baguettebox-js', $init_js); }); // 给图片增加 data-full 属性,存储原图地址(JS读取) add_filter( 'wp_get_attachment_image_attributes', function( $attr, $attachment ){ if( wp_attachment_is_image($attachment) ){ $full_url = wp_get_attachment_url($attachment->ID); $attr['data-full'] = esc_url($full_url); } return $attr; }, 10, 2 );
上面的代码直接复制即可,然后粘贴到wordpress网站主题或子主题的functions.php文件中,也可以添加到wp code之类的代码管理插件中,保存之后可以清空一下缓存。这个代码的好处是直接添加就生效,不用做任何设置。
如上图所示,只要你的文章或页面中添加了wordpress自带的【图库】模块,它就会自动附加灯箱弹出放大效果。
以上代码适合需求简单,同时又不想安装插件的用户。如果你需要更好的图片灯箱效果,也可以安装第3方wordpress插件。
推荐阅读:
给自带相册模块添加灯箱弹出效果
© Copyright 2020~2026. 悦然网络工作室/悦然wordpress建站 专注中小企业wordpress建站 All Rights Reserved.网站地图本站图片来源为Pexels、Pixabay、Freepik、Unsplash等图片库的免费许可,CC0协议;还有部分为自己手绘或AI生成,版权碰瓷请自重!法律服务:law@yueranseo.com蜀ICP备20016391号-1 川公网安备 51011502000367号