How to delete the original image after Crop?

Asked

Viewed 28 times

1

Through the area media Wordpress, it is possible to add images.

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

inserir a descrição da imagem aqui

However when generating the Crop, the original image is maintained, which is a problem since these images usually have more than 5MB.

How to delete the original image after cropping the image?

  • Delete only the jpg/png file? Or in any way the attachment?

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, is only one way to start. There are a thousand things that can go wrong in the middle, because media in WP is really complicated.

  • Hello Ricardo. Thank you for your time. The solution did not work. Continue to generate a new image and keep the original.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.