Last active
December 5, 2017 00:48
-
-
Save soderlind/20a495ae41d1df3854290691aaf9e1a6 to your computer and use it in GitHub Desktop.
WordPress snippet: Use Cloudinary JPGmini add-on to minify jpg site icons and jpg in content.
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 | |
add_filter( 'the_content', function ( $content ) { | |
$doc = new DOMDocument(); | |
// modify state | |
$libxml_previous_state = libxml_use_internal_errors( true ); | |
$doc->loadHTML( $content ); | |
// handle errors | |
libxml_clear_errors(); | |
// restore | |
libxml_use_internal_errors( $libxml_previous_state ); | |
$doc->preserveWhiteSpace = false; | |
$images = $doc->getElementsByTagName( 'img' ); | |
$cloudinary_imgs = array(); | |
foreach ( $images as $img ) { | |
$url = $img->getAttribute( 'src' ); | |
// if images is hosted at cloudinary | |
if ( false !== stripos( $url, 'cloudinary' ) ) { | |
$cloudinary_imgs[] = $img; | |
} | |
} | |
$remove_images = array(); | |
foreach ( $cloudinary_imgs as $cloudinary_image ) { | |
$url = $cloudinary_image->getAttribute( 'src' ); | |
if ( '.jpg' === strrchr( $url, '.' ) ) { | |
$cloudinary_image->setAttribute( 'src', convert_to_jpg_minfy( $url ) ); | |
} | |
} | |
return $doc->saveHTML(); | |
}, 10, 1 ); | |
add_filter( 'site_icon_meta_tags', function( $meta_tags ) { | |
$minified_tags = array(); | |
foreach ($meta_tags as $metatag) { | |
preg_match_all( '/href=\"([^\"]*)\"{1}/', $metatag, $matches ); | |
if ( isset( $matches[1][0] ) ) { | |
$org_url = $matches[1][0]; | |
$minified_url = convert_to_jpg_minfy( str_replace( array( '.png', '.gif' ), '.jpg', $org_url) ); | |
$minified_tags[] = str_replace( $org_url, $minified_url, $metatag ); | |
} | |
} | |
return $minified_tags; | |
}, 10, 1 ); | |
if (! class_exists( 'Cloudinary' ) ) { | |
require_once dirname( __FILE__ ) . '/cloudinary/Cloudinary.php'; // from https://github.com/cloudinary/cloudinary_php/tree/master/src | |
} | |
function convert_to_jpg_minfy( $url ) { | |
try { | |
\Cloudinary::config(array( | |
'cloud_name' => 'CLOUDNAME', | |
'api_key' => 'API KEY', | |
'api_secret' => 'API SECRET', | |
)); | |
$url = cloudinary_url( basename( $url ) , array( | |
'quality' => 'jpegmini', | |
'sign_url' => true, | |
) ); | |
} catch ( \Exception $e ) { | |
write_log( $e->getMessage() ); | |
} | |
return $url; | |
} | |
if ( ! function_exists( 'write_log' ) ) { | |
function write_log( $log ) { | |
if ( is_array( $log ) || is_object( $log ) ) { | |
error_log( print_r( $log, true ) ); | |
} else { | |
error_log( $log ); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Prerequisite, you've added the images using the Cloudinary WordPress plugin