Add suffix to filename of uploaded images

I did it in a different way. I just had to update the code from Gerasimos Tsiamalos Retina Plugin to WordPress 3.5., using image editor instead of image resize.

This is how it looks like:

function nothing_image_make_retina_size($file, $width, $height, $crop=false) {
    if ( $width || $height ) {
        $resized_file = wp_get_image_editor($file);
        if ( ! is_wp_error( $resized_file ) ) {
            $resized_file->resize( $width*2, $height*2, $crop );
            $filename = $resized_file->generate_filename( $width . 'x' . $height . '@2x'  );
            $resized_file->save($filename);
        }
        if ( !is_wp_error($resized_file) && $resized_file && $info = getimagesize($filename) ) {
            $filename = apply_filters('nothing_retina_image_make_intermediate_size', $filename);
            return array(
                'file' => wp_basename( $filename ),
                'width' => $info[0],
                'height' => $info[1],
            );
        }
    }
    return false;
}

function nothing_generate_retina_image_metadata( $metadata, $attachment_id ) {
    $attachment = get_post( $attachment_id );   
    $file = get_attached_file($attachment_id);
    $old_metadata = $metadata;
    foreach ($metadata as $k => $v) {
        if (is_array($v)) {
            foreach ($v as $key => $val) {
                if (is_array($val)) {
                    nothing_image_make_retina_size($file, $val['width'], $val['height'], true);
                } 
            } 
        } 
    }
    return $old_metadata;
}
add_filter('wp_generate_attachment_metadata', 'nothing_generate_retina_image_metadata', 10, 2);

function nothing_delete_retina_images( $attachment_id ) {
    $nothing_metas = wp_get_attachment_metadata( $attachment_id );
    $nothing_updir = wp_upload_dir();
    $nothing_path = pathinfo($nothing_metas['file']);
    $nothing_path_name = $nothing_path['dirname'];
    $nothing_updir = wp_upload_dir();
    foreach ($nothing_metas as $nothing_meta => $nothing_meta_val) {
        if ($nothing_meta === "sizes") {
            foreach ($nothing_meta_val as $nothing_sizes => $nothing_size) {
                $nothing_original_filename = $nothing_updir['basedir'] . "https://wordpress.stackexchange.com/" . $nothing_path_name . "https://wordpress.stackexchange.com/" . $nothing_size['file'];
                $nothing_x2_filename = substr_replace($nothing_original_filename, "@2x.", strrpos($nothing_original_filename, "."), strlen("."));
                if (file_exists($nothing_x2_filename)) {
                    unlink($nothing_x2_filename);
                }
            }           
        }       
    }
}
add_filter('delete_attachment','nothing_delete_retina_images');

Leave a Comment