该方法适用于wordpress 3.6以上版本:
1、在要调用wordpress图片上传功能的页面添加以下代码:
<?php wp_enqueue_media();?>
<script>
jQuery(document).ready(function(){
var upload_frame;
var value_id;
jQuery('.upload_button').live('click',function(event){
value_id =jQuery( this ).attr('id');
event.preventDefault();
if( upload_frame ){
upload_frame.open();
return;
}
upload_frame = wp.media({
title: 'Insert image',
button: {
text: 'Insert',
},
multiple: false
});
upload_frame.on('select',function(){
attachment = upload_frame.state().get('selection').first().toJSON();
jQuery('input[name='+value_id+']').val(attachment.url);
});
upload_frame.open();
});
});
</script>
2、在需要添加图片上传的地方添加以下代码:
<input type="text" size="60" value="" name="upload" id="upload_input"/>
<a id="upload" class="upload_button button" href="#">上传</a>
添加完成后,上传效果如下:
该方法适用于wordpress 3.6之前的版本:
1、在要调用wordpress图片上传功能的页面添加以下代码:
<?php
wp_enqueue_script('media-upload');
wp_enqueue_script('thickbox');
wp_enqueue_script('my-upload');
wp_enqueue_style('thickbox');
?>
<script>
jQuery(document).ready(function() {
jQuery('#upload_image_button').click(function() {
formfield = jQuery('#upload_image').attr('name');
// show WordPress' uploader modal box
tb_show('', '<?php echo admin_url(); ?>media-upload.php?type=image&TB_iframe=true');
return false;
});
window.send_to_editor = function(html) {
// this will execute automatically when a image uploaded and then clicked to 'insert to post' button
imgurl = jQuery('img',html).attr('src');
// put uploaded image's url to #upload_image
jQuery('#upload_image').val(imgurl);
tb_remove();
}
});
</script>
2、在需要添加图片上传的地方添加以下代码:
<input name="pic" id="upload_image" type="text" value="" />
<input id="upload_image_button" type="button" value="上传图片" />
添加完成后,上传效果如下: