I know there’s a lot of similar questions about this, but I couldn’t find and aswer that works for me. I’m sure I’m just missing a detail somehwere.

I’m trying to make an metabox whichwill allow the user to upload pdf into a post. Everything is working so far, except that the field with the url is not saving. Here’s the code:

/* REGISTER THE METABOXES */
function file_metabox_register($post){
    add_meta_box('cpt_file_meta_box', "Upload do Arquivo", 'file_metabox_build', 'file', 'normal', 'low');
}
add_action('add_meta_boxes', 'file_metabox_register');

/* METABOX DESIGN */
function file_metabox_build($post){
    wp_nonce_field(plugin_basename(__FILE__), 'file_metabox_nonce');
    $url_file = get_post_meta($post->ID, '_url_file', true);

    $output .= '<input id="btn_upload_pdf" class="button" type="button" value="Select file"/>';
    $output .= '<br><input id="url-file" type="text" name="url-file" value="'. esc_url($url_file) . '"/>';
    echo $output;
}

/* SAVING THE METABOX DATA */
function file_metabox_save($post_id){
    if(!isset($_POST['file_metabox_nonce']) || !wp_verify_nonce($_POST['file_metabox_nonce'], basename(__FILE__))){
        return;
    }

    if(defined('DOING_AUTOSAVE') && DOING_AUTOSAVE){ 
        return;
    }

    if(!current_user_can('edit_post', $post_id)){
        return;
    }

    if(isset($_REQUEST['url-file'])){
        update_post_meta($post_id, '_url_file', esc_url_raw($_POST['url-file']));
    }
}
add_action('pre_post_update', 'file_metabox_save');

and here’s the JS, that calls WP upload thingy

jQuery(document).ready(function($) {
    var formfield = null;
    $("#btn_upload_pdf").click(function() {
        $("html").addClass("pdf");
        formfield = $("#url-file").attr("name");
        tb_show("", "media-upload.php?type=file&TB_iframe=true");
        return false;
    });

    window.original_send_to_editor = window.send_to_editor;
    window.send_to_editor = function(html){
        var fileurl;
        if (formfield !== null){
            fileurl = $(html).filter('a').attr('href');
            $('#url-file').val(fileurl);
            tb_remove();
            $('html').removeClass('pdf');
            formfield = null;
        }else{
            window.original_send_to_editor(html);
        }
    };
});

Read more here: Saving wordpress metabox


Solution:

If you know the solution of this issue, please leave us a reply in Comment section, to update the question.


Wordpress related questions and answers: