Skip to content

Instantly share code, notes, and snippets.

@matesnippets
Created December 26, 2014 23:42
Show Gist options
  • Save matesnippets/787b10c0926bc4c36fc1 to your computer and use it in GitHub Desktop.
Save matesnippets/787b10c0926bc4c36fc1 to your computer and use it in GitHub Desktop.
PHP, WP, Lazyload images inserted into post body
/**
* Lazy load images inserted into the post body
* @link http://wptheming.com/2013/03/lazy-loading-images/
*/
function add_image_placeholders($content)
{
// Don't lazyload for feeds
if (is_feed()) {
return $content;
}
// Don't lazy-load if the content has already been run through previously
if (false !== strpos($content, 'data-src')) {
return $content;
}
// The placeholder image as data uri
$data_uri_img = 'data:image/gif;base64,R0lGODlhAQABAIAAAMLCwgAAACH5BAAAAAAALAAAAAABAAEAAAICRAEAOw==';
// The regex patterns
$regex_pattern = '#<img([^>]+?)src=[\'"]?([^\'"\s>]+)[\'"]?([^>]*)>#';
// Placeholder image in all its glory
$placeholder_image = apply_filters('lazyload_images_placeholder_image', $data_uri_img);
// Replacement
$replacement = sprintf('<img${1}src="%s" data-src="${2}"${3}><noscript><img${1}src="${2}"${3}></noscript>', $placeholder_image);
// Do the needed regex
$content = preg_replace($regex_pattern, $replacement, $content);
return $content;
}
add_filter('the_content', 'add_image_placeholders', 99);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment