DeveWork

续:WordPress 文章图片部署真正的懒加载(Lazy Load)

几天前分享了《WordPress 中部署真正的懒加载(Lazy Load)》一文,教会了大家在WordPress 中的两个地方部署懒加载:缩略图、头像图片。今天则深入一点,是对在文章页的图片部署懒加载(Lazy Load)。

文章页的图片部署懒加载,手动修改代码?

熟悉懒加载(Lazy Load)插件用法的朋友都知道,可知要实现懒加载,图片img 标签必须如下面那样写:


对于文章页的图片,我们在编辑的时候常常是在可视化编辑器中插入图片的,按照传统的方法,要部署懒加载,必须切换到html 模式下手动修改代码——如此费时费力,傻子才会这么干。

我们可以利用正则表达式+WordPress 强大的过滤器机制,自动替换img 标签的代码。

解放双手,真正的懒加载来也!

将下面的代码加入到主题的functions.php 文件下:

function add_image_placeholders( $content ) {
    // Don't lazyload for feeds, previews, mobile
    if( is_feed() || is_preview() || ( function_exists( 'is_mobile' ) && is_mobile() ) )
        return $content;

    // Don't lazy-load if the content has already been run through previously
    if ( false !== strpos( $content, 'data-original' ) )
        return $content;

    // In case you want to change the placeholder image
    $placeholder_image = apply_filters( 'lazyload_images_placeholder_image', get_template_directory_uri() . '/images/image-pending.gif' );

    // This is a pretty simple regex, but it works
    $content = preg_replace( '#]+?)src=[\'"]?([^\'"\s>]+)[\'"]?([^>]*)>#', sprintf( '', $placeholder_image ), $content );

    return $content;
}
add_filter( 'the_content', 'add_image_placeholders', 99 );

该段代码的含义已经有注释了(虽然是英文,但很简单),在此不累赘~

相应的,懒加载(Lazy Load)的激活代码最好修改为以下:

jQuery("img").lazyload({ 
   .............//中间的代码忽略	
    }); 

就是默认对所有img 标签开启懒加载。

最上面的代码来自于wptheming ,灰常感谢原作者!