在主题和插件开发中我们经常希望用户能再前端上传图片,例如上传头像、投稿等功能都涉及到图片上传,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>
完成后会有以下效果:
一日程新手WP建站指南(https://www.yiricheng.cn/),为广大编程爱好者提供零基础快速搭建博客网站的方法,分享计算机网络、HTML、CSS、JavaScript、PHP、响应式设计以及Python自动化办公的博客文章,另有各类小工具、电子书、免费教程。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。