Upload Video or Image in WordPress Media Library

Upload Video or Image in WordPress  Media Library

When we use custom form with file upload and we want to upload Video or Image in wordpress media library use following code.

<?php

if (!function_exists('wp_generate_attachment_metadata')){
    require_once(ABSPATH . "wp-admin" . '/includes/image.php');
    require_once(ABSPATH . "wp-admin" . '/includes/file.php');
    require_once(ABSPATH . "wp-admin" . '/includes/media.php');
}
if(isset($_POST['submit'])){
    $attach_id = '';
    if ($_FILES['thumbnail']['name']) { //specify here input field name
        foreach ($_FILES as $file => $array) {
            if ($_FILES[$file]['error'] !== UPLOAD_ERR_OK) {
                return "upload error : " . $_FILES[$file]['error'];
            }
            $attach_id = media_handle_upload( $file, 0 );
        }
    }
}

?>
Was this article helpful?
YesNo

Leave a comment

Your email address will not be published. Required fields are marked *