Cropping an image before inserting into a post
I've got a frontend post form, and I've been using this PHP code to allow uploading an image and to insert it into a post.
// image upload and attatching to post
if ( ! empty( $_FILES ) ! empty( $_FILES['upload-image']['name'] ) ) {
// upload image to server
$upload = wp_upload_bits( $_FILES['upload-image']['name'], null, file_get_contents( $_FILES['upload-image']['tmp_name'] ) );
// insert new image to the just created post ================================
$wp_filetype = wp_check_filetype( basename( $upload['file'] ), null );
$wp_upload_dir = wp_upload_dir();
$attachment = array(
'guid' = $wp_upload_dir['baseurl'] . _wp_relative_upload_path( $upload['file'] ),
'post_mime_type' = $wp_filetype['type'],
'post_title' = preg_replace('/\.[^.]+$/', '', basename( $upload['file'] )),
'post_content' = '',
'post_status' = 'inherit'
);
$attach_id = wp_insert_attachment( $attachment, $upload['file'], $post_id );
require_once(ABSPATH . 'wp-admin/includes/image.php');
$attach_data = wp_generate_attachment_metadata( $attach_id, $upload['file'] );
wp_update_attachment_metadata( $attach_id, $attach_data );
update_post_meta( $post_id, '_thumbnail_id', $attach_id );
// end insert ==============================================
}
How can I ensure that all images are cropped to a 16:9 aspect ratio, before it is inserted into the post? So if the image's height is too high, it crops the top and bottom to fit it into 16:9 ratio, and if the image's width is too wide, it crops the sides to fit it into 16:9 ratio.
I've found a function that always crops the image to a 16:9 ratio here that I could base it on: https://stackoverflow.com/questions/29063094/php-fit-any-size-image-to-169-aspect-ratio (not tested). But I'm not sure how to use this in my above code above - the 16:9 ratio image needs to be ready before inserting into the post.
Any help appreciated.
Topic wp-insert-post cropping images Wordpress
Category Web