Image clipping in wordpress and deleting the original image

Question:

After uploading an image on wordpress I would like to check if the registered image is larger than the declared size limit, if it is larger I want to delete the original image in the upload folder and keep only the images cropped with thumbnails (media).

I'm using this function in functions.php

add_filter( 'wp_generate_attachment_metadata', 'delete_fullsize_image' );
function delete_fullsize_image( $metadata )
{
    $upload_dir = wp_upload_dir();
    $full_image_path = trailingslashit( $upload_dir['basedir'] ) . $metadata['file'];
    $deleted = unlink( $full_image_path );

    return $metadata;
}

Example:

I have specified that the maximum size of the images will be 300×300, when uploading a 350×350 image it will crop the image to the size of 300×300 and delete the original 350×350 image.

How is it possible to do this?

Answer:

Apply to functions.php file

add_filter( 'wp_generate_attachment_metadata', 'delete_fullsize_image' );
function delete_fullsize_image( $metadata )
{
    $upload_dir = wp_upload_dir();
    $full_image_path = trailingslashit( $upload_dir['basedir'] ) . $metadata['file'];
    if($metadata['width'] >= '300'){
     $deleted = unlink( $full_image_path );
    }    
    return $metadata;
}

With this function you can get the image width before uploading . In this case, the limit value is 300.

Scroll to Top