How to Add a Media Uploader to a Custom Form in WordPress
If you want to add a WordPress file upload to your form so that when you select a photo or video, its URL will be added to your input field, you can use this code.
- This HTML code must be used in the form
<label for="upload_file">
<input id="upload_file" type="text" size="36" name="fileLink" value="" />
<input id="upload_file_button" class="button" type="button" value="Upload File" />
<br />Enter a URL or upload an File
</label>
- This PHP code must be used in the theme function.php or plugin php file.
<?php
add_action( 'admin_enqueue_scripts', 'my_admin_scripts' );
function my_admin_scripts() {
if ( isset( $_GET['page'] ) && $_GET['page'] == 'my_plugin_page' ) {
wp_enqueue_media();
wp_register_script( 'my-admin-js', WP_PLUGIN_URL.'/my-plugin/my-admin.js', array( 'jquery' ) );
wp_enqueue_script( 'my-admin-js' );
}
}
?>
- This jQuery code must be used in the JS file.
jQuery(document).ready(function($){
var customUploader;
$('#upload_file_button').click(function(e) {
e.preventDefault();
//If the uploader object has already been created, reopen the dialog
if (customUploader) {
customUploader.open();
return;
}
//Extend the wp.media object
customUploader = wp.media.frames.file_frame = wp.media({
title: 'Choose File',
button: {
text: 'Choose File'
},
multiple: true
});
//When a file is selected, grab the URL and set it as the text field's value
customUploader.on('select', function() {
console.log(customUploader.state().get('selection').toJSON());
attachment = customUploader.state().get('selection').first().toJSON();
$( '#upload_file' ).val( attachment.url );
});
//Open the uploader dialog
customUploader.open();
});
});