Skip to content

Instantly share code, notes, and snippets.

@KZeni
Created October 28, 2013 21:22
Show Gist options
  • Save KZeni/7205026 to your computer and use it in GitHub Desktop.
Save KZeni/7205026 to your computer and use it in GitHub Desktop.
Modified wr2x_srcset_rewrite function for Retina 2x WordPress plugin that fixes the [partial] stripping of HTML tags when using the HTML srcset option. This is the all-new function that follows the HTML rewrite's method of adding the retina image's code.
function wr2x_srcset_rewrite( $buffer ) {
if ( !isset( $buffer ) || trim( $buffer ) === '' )
return $buffer;
$doc = new DOMDocument();
@$doc->loadHTML( $buffer ); // = ($doc->strictErrorChecking = false;)
$imageTags = $doc->getElementsByTagName('img');
foreach ( $imageTags as $tag ) {
$img_info = parse_url( $tag->getAttribute('src') );
$img_pathinfo = ltrim( $img_info['path'], '/' );
$filepath = trailingslashit( ABSPATH ) . $img_pathinfo;
$potential_retina = wr2x_get_retina( $filepath );
if ( $potential_retina != null ) {
wr2x_log( "Add srcset: " . $potential_retina . ' 2x' );
$retina_pathinfo = ltrim( str_replace( ABSPATH, "", $potential_retina ), '/' );
$retina_url = trailingslashit( get_site_url() ) . $retina_pathinfo;
$img_url = trailingslashit( get_site_url() ) . $img_pathinfo;
$buffer = str_replace( 'src="'.$img_url.'"', 'src="'.$img_url.'" srcset="'.$retina_url.' 2x"', $buffer );
}
}
return $buffer;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment