Skip to content

Instantly share code, notes, and snippets.

@Pross
Created July 20, 2021 19:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Pross/29de7512ee5ac05596a1cf66bcb038ed to your computer and use it in GitHub Desktop.
Save Pross/29de7512ee5ac05596a1cf66bcb038ed to your computer and use it in GitHub Desktop.
Convert all urls in layout css to base64 encoded data urls.
<?php // this lines just here so the formatting works, ignore it.
add_filter( 'fl_builder_render_css', function( $css, $nodes, $global_settings, $include_global ) {
if ( isset( $_GET['fl_builder'] ) ) {
return $css;
}
// keep original in case this goes tits up
$original = $css;
$parse = preg_match_all( '/(https?:\/\/.*\.(?:png|jpe?g|gif|webp))/', $css, $urls, PREG_PATTERN_ORDER );
if ( ! $parse ) {
return $original;
}
foreach ( $urls[0] as $url ) {
$path = str_ireplace( home_url(), untrailingslashit( ABSPATH ), $url );
if ( is_file( $path ) ) {
$type = exif_imagetype( $path );
$typestring = null;
switch ( $type ) {
case IMG_GIF:
$typestring = 'image/gif';
break;
case IMG_JPG:
$typestring = 'image/jpg';
break;
case IMG_JPEG:
$typestring = 'image/jpeg';
break;
case IMG_PNG:
$typestring = 'image/png';
break;
case IMAGETYPE_WEBP:
$typestring = 'image/webp';
break;
default:
$typestring = 'unknown';
}
if ( 'unknown' !== $typestring ) {
$data = sprintf( 'data:%s;base64,%s', $typestring, base64_encode( file_get_contents( $path ) ) );
$css = str_replace( $url, $data, $css );
}
}
}
return $css;
}, 10, 4 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment