wordpress自带的媒体中心具有便捷的附件或图片上传功能,而在制作主题或插件时往往会需要用到上传功能,比如上传LOGO、上传照片或投稿时上传附件等,如果自己编写上传功能不仅麻烦且浪费时间,而wordpress早就已经考虑到了这一些问题,因此集成了相关的一些函数提供给开发者,以便节省开发的时间成本。
PS:确认调用的页面已经引入jquery库,否则无效!
该方法适用于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="上传图片" />
添加完成后,上传效果如下:

PS:不要随便开发上传功能给网站用户,避免用户上传一些不安全的东西!
原文链接:https://www.fogwhale.cn/?p=1076,转载请注明出处。
评论0