Created
March 21, 2017 15:58
-
-
Save kingkool68/a3515932d2409427c5d399aaf2de6fe8 to your computer and use it in GitHub Desktop.
Lazy Load Images WordPress Plugin for Boagworld
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* | |
Plugin Name: Bogworld's Special Neat-o Plugin | |
Description: See https://twitter.com/boagworld/status/844200551017562112 | |
Author: kingkool68 | |
Version: 0.0.1 | |
Author URI: https://twitter.com/kingkool68 | |
*/ | |
/* | |
Take any image with the Sirv class, extract the last part of the url, and then replace the original image code with the following adapted url and image code… | |
Input: | |
<img class="Sirv" src="https://boagworld.com/Images/call-to-action/Call-to-Action-1.jpg" /> | |
Output: | |
<img class="Sirv" data-src="https://boagworld-cdn.sirv.com/Images/call-to-action/Call-to-Action-1.jpg" data-options="lazy: true" /> | |
<noscript><img class="Sirv" src="https://boagworld-cdn.sirv.com/Images/call-to-action/Call-to-Action-1.jpg" /></noscript> | |
*/ | |
function boagworld_sirv_and_replace( $content = '' ) { | |
// If class="Sirv" isn't found, then bail, nothing more to do | |
if ( ! stristr( $content, 'class="Sirv"' ) ) { | |
return $content; | |
} | |
$dom = new DOMDocument; | |
$dom->loadHTML( $content ); | |
$xpath = new DOMXPath( $dom ); | |
$nodes = $xpath->query( '//img[contains(@class, "Sirv")]' ); | |
foreach ( $nodes as $node ) { | |
$src = $node->getAttribute( 'src' ); | |
$new_src = str_replace( 'https://boagworld.com', 'https://boagworld-cdn.sirv.com', $src ); | |
$node->removeAttribute( 'src' ); | |
$node->setAttribute( 'data-src', $new_src ); | |
$node->setAttribute( 'data-options', 'lazy:true' ); | |
$fallback_img = $dom->createElement( 'img' ); | |
$fallback_img->setAttribute( 'class', 'Sirv' ); | |
$fallback_img->setAttribute( 'src', $new_src ); | |
$noscript = $dom->createElement( 'noscript' ); | |
$noscript->appendChild( $fallback_img ); | |
$node->parentNode->appendChild( $noscript ); | |
} | |
$content = $dom->saveHTML(); | |
return $content; | |
} | |
add_filter( 'the_content', 'boagworld_sirv_and_replace' ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment