Using the WordPress media library in your own plugin/theme will save you a bunch of time. This blog will provide an example of how to use the Media Library in a plugin/theme environment.
When using wp.media, there are a few things that we are interested. The first one is how to define the media frame.
ENQUEUE THE SCRIPT
<?php /* Add the media upload script */ function wk_enqueue_script() { //Enqueue media. wp_enqueue_media(); // Enqueue custom js file. wp_register_script( 'wk-admin-script', plugins_url( __FILE__ ), array('jquery') ); wp_enqueue_script( 'wk-admin-script' ); } add_action('admin_enqueue_scripts', 'wk_enqueue_script'); ?>
var wkMedia; // Extend the wp.media object wkMedia = wp.media.frames.file_frame = wp.media({ title: 'Choose Image', button: { text: 'Choose Image' }, multiple: false });
This article will just show the code snippets that you need to use in order to get everything to work. The rest will be up to you to incorporate into your plugin/theme.
Form
//Form html <form method="post"> <input id="wk-media-url" type="text" name="media" /> <input id="wk-button" type="button" class="button" value="Upload Image" /> <input type="submit" value="Submit" /> </form>
We need some html tags in order to select media file and these are:-
- A text input where we will put the URL of the file we select.
- A button that will activate the WordPress media library.
- Finally a submit button so that you can do something with the URL.
The second thing that we are interested in is how to capture the event when we have selected the image(s) and clicked on the Select button.
// When a file is selected, grab the URL and set it as the text field's value wkMedia.on('select', function() { var attachment = wkMedia.state().get('selection').first().toJSON(); $('#wk-media-url').val(attachment.url); });
JavaScript Code Example
jQuery(document).ready(function($){ // Define a variable wkMedia var wkMedia; $('#wk-button').click(function(e) { e.preventDefault(); // If the upload object has already been created, reopen the dialog if (wkMedia) { wkMedia.open(); return; } // Extend the wp.media object wkMedia = wp.media.frames.file_frame = wp.media({ title: 'Select media', button: { text: 'Select media' }, multiple: false }); // When a file is selected, grab the URL and set it as the text field's value wkMedia.on('select', function() { var attachment = wkMedia.state().get('selection').first().toJSON(); $('#wk-media-url').val(attachment.url); }); // Open the upload dialog wkMedia.open(); }); });
Support
Still have any issue feel free to add a ticket and let us know your views to make the code better https://webkul.uvdesk.com/en/customer/create-ticket/
Thanks for Your Time! Have a Good Day!
4 comments
Thanks for the appreciation.
In case of further queries please mail us at [email protected].
With Regards,
Webkul Team
Thanks for the appreciation.
In case of further queries please mail us at [email protected].
With Regards,
Webkul Team