我有一个前端帖子表单,我一直在使用这个PHP代码来允许上传一个图像并将其插入帖子。
// 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 ==============================================
}
如何确保在将所有图像插入帖子之前,将其裁剪为16:9的纵横比?因此,如果图像的高度太高,它会将顶部和底部裁剪成16:9的比例,如果图像的宽度太宽,它会将侧面裁剪成16:9的比例。我在这里找到了一个函数,它总是将图像裁剪成16:9的比例,我可以根据这个比例进行计算:https://stackoverflow.com/questions/29063094/php-fit-any-size-image-to-169-aspect-ratio (未测试)。但我不知道如何在我上面的代码中使用它-16:9的比例图像需要在插入帖子之前准备好。
感谢您的帮助。