为WordPress文章图片自动添加链接到原图
为WordPress文章图片自动添加链接到原图是为了图片灯箱效果。
灯箱效果需要链向自身的a标签,并且a标签里要有data-imgbox="imgbox"属性(其他灯箱实现方法可能不一样)。
function方法
有缺陷,只有图片本身没有a标签时可以使用。
//wordpress图片自动添加链接
add_filter('the_content', 'fancybox1');
add_filter('the_content', 'fancybox2');
function fancybox1($content){
global $post;
$pattern = "/<img(.*?)src=('|\")([^>]*).(bmp|gif|jpeg|jpg|png|swf)('|\")(.*?)>/i";
$replacement = '<a$1href=$2$3.$4$5 data-imgbox="imgbox"><img$1src=$2$3.$4$5$6></a>';
$content = preg_replace($pattern, $replacement, $content);
return $content;
}
function fancybox2($content){
global $post;
$pattern = "/<a(.*?)href=('|\")([^>]*).(bmp|gif|jpeg|jpg|png|swf)('|\")(.*?)>(.*?)<\/a>/i";
$replacement = '<a$1href=$2$3.$4$5 data-imgbox="imgbox"$6>$7</a>';
$content = preg_replace($pattern, $replacement, $content);
return $content;
}
相关阅读:https://www.wuzuowei.net/16903.html
其他方法:javascript
//为WordPress文章图片自动添加链接到原图
<script type="text/javascript">
$(function() {
$('.entry img').each(function(i){
if (! this.parentNode.href) {
$(this).wrap("<a href='"+this.src+"' data-imgbox='imgbox'></a>");
}
});
});
</script>
修改其中的 .entry 为你主题正文的CSS类。
相关阅读:https://zmingcx.com/wordpress-pictures-auto-add-links.html
文章目录
本作品采用 知识共享署名-相同方式共享 4.0 国际许可协议 进行许可。