I’m trying to create a metabox in WordPress that allows the user to select a PDF file to attach to the post he/she is creating. So far, the metabox shows well, and the media uploader works as expected to certain extent.

The problem is that when the user clicks in the browse button, the default media uploader will show first. If I close that one and click the button again, then the custom uploader will show up and work as expected. Here is the JS code I’m using…

jQuery(document).ready(function($){
// Instantiates the variable that holds the media library frame.
var pdf_file_frame;
// Runs when the image button is clicked.
$('#pdf-lesson-url-button').click(function(e){
    // Prevents the default action from occurring.
    e.preventDefault();
    // If the frame already exists, re-open it.
    if ( pdf_file_frame ) {
        pdf_file_frame.open();
        return;
    }
    // Sets up the media library frame
    pdf_file_frame = wp.media.frames.file_frame = wp.media({
        title: pdf_meta.title,
        button: { text:  pdf_meta.button },
        library: { type: 'application/pdf' },
        multiple: false
    });
    // Runs when an image is selected.
    pdf_file_frame.on('select', function(){
        // Grabs the attachment selection and creates a JSON representation of the model.
        var media_attachment = pdf_file_frame.state().get('selection').first().toJSON();
        // Sends the attachment URL to our custom image input field.
        $('#pdf-lesson-url').val(media_attachment.url);
    });
    // Opens the media library frame.
    wp.media.editor.open();
});

});

I have googled the issue but no satidfactory results came out. I might be using the wrong search phrase, but the truth is that I have no idea of what is happening here, especially when once you get the custom dialog to show it works OK.

Any help is highly appreciated.

Thanks to all who read this post.

Read more here: Custom media uploader in WordPress shows after default media uploader


Solution:

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

Related Wordpress search:

, , , , ,

Wordpress related questions and answers: