I am developing a wordpress plugin and I need to have a field where I can upload an image. Since wordpress has a very handly uploader it would be great if I could use that.
anyone know if that's possible?
Thanks
Simply put the shortcode [wordpress_file_upload] to the contents of any WordPress page / post or add the plugin's widget in any sidebar and you will be able to upload files to any directory inside wp-contents of your WordPress site. You can add custom fields to submit additional data together with the uploaded file.
Upload the “Auto Upload Images” to plugin directory and Activate it. To change settings go to “Settings > Auto Upload Images” and change it.
If you only want to upload a file, you don't need the media uploader. A simple form is all you need.
To call the media uploader you need a link like this:
<a onclick="return false;" title="Upload image" class="thickbox" id="add_image" href="media-upload.php?type=image&TB_iframe=true&width=640&height=105">Upload Image</a>
You'll maybe have to append your URL to media-upload.php to make it working.
YOu can use wordpress default media file uploader by using this code and simply retrieve link of image in jquery
<label for="upload_image">
<input id="upload_image" type="text" size="36" name="ad_image" value="http://" />
<input id="upload_image_button" class="button" type="button" value="Upload Image" />
<br />Enter a URL or upload an image
</label>
<?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');
}
}
?>
<script>
jQuery(document).ready(function($){
var custom_uploader;
$('#upload_image_button').click(function(e) {
e.preventDefault();
//If the uploader object has already been created, reopen the dialog
if (custom_uploader) {
custom_uploader.open();
return;
}
//Extend the wp.media object
custom_uploader = wp.media.frames.file_frame = wp.media({
title: 'Choose Image',
button: {
text: 'Choose Image'
},
multiple: true
});
//When a file is selected, grab the URL and set it as the text field's value
custom_uploader.on('select', function() {
console.log(custom_uploader.state().get('selection').toJSON());
attachment = custom_uploader.state().get('selection').first().toJSON();
$('#upload_image').val(attachment.url);
});
//Open the uploader dialog
custom_uploader.open();
});
});
</script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With