How do I upload file through custom field, save it to database and get it

If you want to add the file to the WordPress Media Library, you can use media_handle_upload(). The function returns the attachment post ID on success, so you can save that in a post meta and then use the relevant function to get the attachment/file details, e.g. wp_get_attachment_url() can be used to get the attachment URL.

So for example:

  • In cd_meta_box_cb(), this will add the file upload input and (for demo purpose) displays the current video URL, if any, before that input:

    <?php
    $video_id  = (int) get_post_meta( $post->ID, 'my_video_id', true );
    $video_url = $video_id ? wp_get_attachment_url( $video_id ) : '';
    
    echo 'Current video URL: ' . esc_url( $video_url ) . '<br />';
    ?>
    <input type="file" name="my_video_file" accept="video/*" />
    
  • In cd_meta_box_save(), this will add the video to the media library and save the attachment (post) ID in a post meta named my_video_id:

    if ( isset( $_FILES['my_video_file'] ) ) {
        // Add the file to the media library.
        $video_id = media_handle_upload( 'my_video_file', $post_id );
    
        // Save the video/attachment ID in a post meta.
        if ( ! is_wp_error( $video_id ) ) {
            update_post_meta( $post_id, 'my_video_id', $video_id );
        }
    }
    

And if you just wanted to upload the file to the WordPress uploads directory (wp-content/uploads), i.e. without adding the file to the media library, then you can use wp_handle_upload(), but please check the documentation for usage syntax and also examples.