Upload images and videos to WP Media Library via custom form

Question

I am trying to upload images and videos to wp media library via a custom registration form i made. I only need to upload the files I select to WP media library, so I can retrieve them after the upload.

This is my code so far:

function upload_files($files_array){
    $wp_upload_dir = wp_upload_dir();

    foreach ($files_array as $file) {

            $filename = $file['name'];
            $filetype = $file['type'];
            $tempname = $file['temp_name'];

            $upload_file = wp_upload_bits($filename, null, file_get_contents($filename));

            if (!$upload_file['error']) {
                $attachment = array(
                    'post_mime_type' => $filetype,
                    'post_title' => preg_replace('/.[^.]+$/', '', $filename),
                    'post_content' => '',
                    'post_status' => 'inherit'
                );
                $attachment_id = wp_insert_attachment( $attachment, $upload_file['file'], $parent_post_id );
                if (!is_wp_error($attachment_id)) {
                    require_once(ABSPATH . "wp-admin" . '/includes/image.php');
                    require_once(ABSPATH . "wp-admin" . '/includes/media.php');
                    $attachment_data = wp_generate_attachment_metadata( $attachment_id, $upload_file['file'] );
                    wp_update_attachment_metadata( $attachment_id,  $attachment_data );
                }
            }

    }
}

I managed to upload only image files but in the media library i get this:

enter image description here

Also if I open the image via its link I get a blank page, like the image was not created properly.

Can anybody help me? I need to sort this ASAP, I am trying everything but I cannot get this to work.

0
d0t_m 4 months 0 Answers 11 views 0

Leave an answer