0

I have form to upload image via Ajax, it's works efficiently.

But image not have preview thumbnail like :

enter image description here

if(isset($_FILES['file'])) {
    require_once( ABSPATH . 'wp-admin/includes/image.php' );
    require_once( ABSPATH . 'wp-admin/includes/file.php' );
    require_once( ABSPATH . 'wp-admin/includes/media.php' );
    require_once( ABSPATH . 'wp-admin/includes/admin.php' );

    $file_return = wp_handle_upload( $_FILES['file'], array('test_form' => false ) );

    if( isset( $file_return['error'] ) || isset( $file_return['upload_error_handler'] ) ) {
        echo $file_return['error'];
    } else {
        $attachment = array(
            'post_mime_type' => $file_return['type'],
            'post_title' => preg_replace( '/\.[^.]+$/', '', basename( $file_return['file'] ) ),
            'post_content' => '',
            'post_status' => 'inherit',
            'guid' => $file_return['url'],
        );

        $attachment_id = wp_insert_attachment( $attachment, date('Y/m/') .  basename($file_return['url']) );

        $attach_data = wp_generate_attachment_metadata( $attachment_id, basename( $file_return['file'] ) );
        wp_update_attachment_metadata( $attachment_id, $attach_data );

        update_field('user_cavatar', $attachment_id, $user_id);
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.