How do I delete the original image after cropping?

1

Through the media area of Wordpress, you can add images.

The problem is that the client does not know how to crop images using an editing program such as Photoshop , so it uses the crop Wordpress :

While generating crop , the original image is retained, which is a problem since these images usually have more than 5MB.

How to delete the original image after cropping the image?

    
asked by anonymous 24.02.2017 / 19:17

1 answer

0

One possible way is to use the action wp_ajax_crop_image_pre_save to replace the original image with the cropped image, something like this:

add_action( 'wp_ajax_crop_image_pre_save', 'sobrescrever_imagem', 10, 3 );

/*
 * Busca a imagem original e substitui pela imagem recortada.
 * atualizando os meta-dados
 */    
function sobrescrever_imagem( $context, $attachment_id, $cropped ) {
    // Busca os metadados originais  
    // https://developer.wordpress.org/reference/functions/wp_get_attachment_metadata/
    $orig_data = wp_get_attachment_metadata( $attachment_id );

    $orig_data['file'] = $cropped;

    // Gera novamente os metadados
    // https://developer.wordpress.org/reference/functions/wp_generate_attachment_metadata/
    $updated_data = wp_generate_attachment_metadata( $attachment_id, $cropped );

    // Salva no attachment original
    // https://developer.wordpress.org/reference/functions/wp_update_attachment_metadata/
    if ( wp_update_attachment_metadata( $attachment_id, $updated_data ) ) {

        // Deleta o original
        $orig_file = $orig_data['file'];
        unlink( $orig_file );
    }
}

This code has not been tested , it's just a way to get started. There are a thousand things that can go wrong in the middle, because media in WP is really complicated.

    
24.02.2017 / 20:09