Skip to content

Instantly share code, notes, and snippets.

@DevWael
Last active November 15, 2017 00:10
Show Gist options
  • Save DevWael/ae5005767f1c9afded77aabe7283afa2 to your computer and use it in GitHub Desktop.
Save DevWael/ae5005767f1c9afded77aabe7283afa2 to your computer and use it in GitHub Desktop.
<?php
/*
Just copy the following code in functions.php file into your theme.
*/
add_action('after_setup_theme','window_mag_retina_script');
function window_mag_retina_script(){
wp_enqueue_script( 'retina-js', 'https://cdnjs.cloudflare.com/ajax/libs/retina.js/2.1.3/retina.min.js', array( 'jquery' ), '1.0', true );
}
/**
* Retina images
*
* This function is attached to the 'wp_generate_attachment_metadata' filter hook.
*/
add_filter( 'wp_generate_attachment_metadata', 'window_mag_retina_support_attachment_meta', 10, 2 );
function window_mag_retina_support_attachment_meta( $metadata, $attachment_id ) {
foreach ( $metadata as $key => $value ) {
if ( is_array( $value ) ) {
foreach ( $value as $image => $attr ) {
if ( is_array( $attr ) && isset ( $attr['width'] ) && isset ( $attr['height'] ) ) {
window_mag_retina_support_create_images( get_attached_file( $attachment_id ), $attr['width'], $attr['height'], true );
}
}
}
}
return $metadata;
}
/**
* Create retina-ready images
*
* Referenced via retina_support_attachment_meta().
*/
function window_mag_retina_support_create_images( $file, $width, $height, $crop = false ) {
if ( $width || $height ) {
$resized_file = wp_get_image_editor( $file );
if ( ! is_wp_error( $resized_file ) ) {
$filename = $resized_file->generate_filename( $width . 'x' . $height . '@2x' );
$resized_file->resize( $width * 2, $height * 2, $crop );
$resized_file->save( $filename );
$info = $resized_file->get_size();
return array(
'file' => wp_basename( $filename ),
'width' => $info['width'],
'height' => $info['height'],
);
}
}
return false;
}
add_filter( 'delete_attachment', 'window_mag_delete_retina_support_images' );
/**
* Delete retina-ready images
*
* This function is attached to the 'delete_attachment' filter hook.
*/
function window_mag_delete_retina_support_images( $attachment_id ) {
$meta = wp_get_attachment_metadata( $attachment_id );
$upload_dir = wp_upload_dir();
if ( isset( $meta['file'] ) ) {
$path = pathinfo( $meta['file'] );
foreach ( $meta as $key => $value ) {
if ( 'sizes' === $key ) {
foreach ( $value as $sizes => $size ) {
$original_filename = $upload_dir['basedir'] . '/' . $path['dirname'] . '/' . $size['file'];
$retina_filename = substr_replace( $original_filename, '@2x.', strrpos( $original_filename, '.' ), strlen( '.' ) );
if ( file_exists( $retina_filename ) ) {
unlink( $retina_filename );
}
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment