We can use native wordpress Media uploader in our themes and plugins to upload the image from the media library.
Following code will include the required scripts and stylesheets for the Media uploader thickbox.
if(!function_exists('custom_uploader_scripts')) {
function custom_uploader_scripts() {
wp_enqueue_script('jquery');
wp_enqueue_script('media-upload');
wp_enqueue_script('thickbox');
}
}
add_action('admin_print_scripts', 'custom_uploader_scripts');
if(!function_exists('custom_uploader_styles')) {
function custom_uploader_styles() {
wp_enqueue_style('thickbox');
}
}
add_action('admin_print_styles', 'custom_uploader_styles');
Following lines will be used to display the input text and the Browse button.
<input type="text" name="input_image_path" id="input_image_path" value=""/>
<input type="button" name="trigger_image_button" id="trigger_image_button" value="Browse" />
Following code can be used in the separate JS file or can be used in the same php file. This will trigger the media uploader and will insert the image url into the text box on image selection.
<script type="text/javascript">
(function($){
$('#trigger_image_button').click(function() {
tb_show('', 'media-upload.php?referer=custom-upload&type=image&TB_iframe=true');
window.send_to_editor = function(html) {
imgurl = $('img',html).attr('src');
$('#input_image_path').val(imgurl);
tb_remove();
return false;
});
})(jQuery);
</script>
In media uploader, by default the save button text will be "Insert into Post", we can customize the text of the button through the following code
if(!function_exists('custom_options_setup')) {
function custom_options_setup() {
global $pagenow;
if ('media-upload.php' == $pagenow || 'async-upload.php' == $pagenow) {
// Now we'll replace the 'Insert into Post Button inside Thickbox'
add_filter( 'gettext', 'replace_thickbox_text' , 1, 2 );
}
}
}
add_action( 'admin_init', 'custom_options_setup' );
if(!function_exists('replace_thickbox_text')) {
function replace_thickbox_text($translated_text, $text ) {
if ( 'Insert into Post' == $text ) {
$referer = strpos( wp_get_referer(), 'custom-upload' );
/* Here the custom-upload text is appended to the url through above JS code. Its to make filter to apply only for our page without disturbing the other media uploaders. */
if ( $referer != '' ) {
return __('Use this Image', 'custom');
}
}
return $translated_text;
}
}
No comments:
Post a Comment