在主题和插件开发中我们经常希望用户能再前端上传图片,例如上传头像、投稿等功能都涉及到图片上传,wordpress自带的媒体中心具有便捷的附件或图片上传功能,下面就分享给大家简单的前端图片上传功能
注意:需要主题或者插件已经引入jquery,否者无效
1、在需要调用到上传图片页面的地步引入一下代码:
- <?php wp_enqueue_media();?>
- <script>
- jQuery(document).ready(function(){
- var upload_frame;
- var value_id;
- jQuery('.upload_button').on('click',function(e){
- value_id =jQuery( this ).attr('id');
- event.preventDefault();
- if( upload_frame ){
- upload_frame.open();
- return;
- }
- upload_frame = wp.media({
- title: '插入图片',
- button: {
- text: '插入',
- },
- multiple: false
- });
- upload_frame.on('select',function(){ //里面是选择图片后的动作,把图片地址赋值给input
- 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"/>
- <a id="upload" class="upload_button button" href="#">上传</a>