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

Question

I have made a custom field without any plugin. When I choose file I want to upload that file and get its url on my page. Basically, I want to upload video and show it on frontend. This is my code right now (its just good for text, not upload file):

function cd_meta_box_cb()
{
    global $post;
    $values = get_post_custom( $post->ID );
    $text = isset( $values['my_meta_box_text'] ) ? $values['my_meta_box_text'][0] : '';
    wp_nonce_field( 'my_meta_box_nonce', 'meta_box_nonce' );
    ?>
    <p>
        <label for="my_meta_box_text">Video URL</label>
        <input type="file"
       id="my_meta_box_text" name="my_meta_box_text" id="my_meta_box_text"
       accept="video/*" value="<?php echo $text; ?>" />
       <input type="hidden" class="hidden-file-field" name="hidden_file_field" />
    </p>
    <?php    
}
add_action( 'save_post', 'cd_meta_box_save' );
function cd_meta_box_save( $post_id )
{
    if( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return;
    if( !isset( $_POST['meta_box_nonce'] ) || !wp_verify_nonce( $_POST['meta_box_nonce'], 'my_meta_box_nonce' ) ) return;
    if( !current_user_can( 'edit_post' ) ) return;
    $allowed = array( 
        'a' => array( // on allow a tags
            'href' => array() 
        )
    );
    if( isset( $_POST['my_meta_box_text'] ) )
        update_post_meta( $post_id, 'my_meta_box_text', wp_kses( $_POST['my_meta_box_text'], $allowed ) );
}

0
Saurabh Jain 2 months 2022-06-23T23:44:21-05:00 0 Answers 0 views 0

Leave an answer

Browse
Browse