Skip to content

Instantly share code, notes, and snippets.

@Alexander-Pop
Forked from thagxt/functions.php
Last active June 28, 2019 14:10
Show Gist options
  • Save Alexander-Pop/fcb5d5c8c2de8654b0fa52d79b0ff316 to your computer and use it in GitHub Desktop.
Save Alexander-Pop/fcb5d5c8c2de8654b0fa52d79b0ff316 to your computer and use it in GitHub Desktop.
WP - Function to add a class to all your "POST" images in WordPress and get them ready for lazyload. #wp
<?php
function lazyload_filter_content($content) {
global $post; // getting The whole post objects
$content = $post->post_content;
if( is_singular() && is_main_query() ) {
//Renaming images for lazy loader!!!
// Replace all image tags with the appropriately formatted HTML
// We add a data-unveil attribute so we can target a CSS transition (fade-in)
$content = preg_replace( '#<img([^>]+?)src=[\'"]?([^\'"\s>]+)[\'"]?([^>]*)>#',
sprintf( '<img${1}src="%s" data-src="${2}"${3} class="unveil"><noscript><img${1}src="${2}"${3}></noscript>', $placeholder ), $content );}
return $content; // returning the edited $content
}
add_filter('the_content', 'lazyload_filter_content');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment