很多人喜欢把图片放在图床上,可以有自建的,或者是第三方图床的,只要图床有api接口都基本能实现对接,具体自己参考
api说明,boxmoe发布的这段代码是比较适合市场绝大部图床的api,只要修改一下 api的posturl post参数和返回参数
复制代码
- //添加图床上传按钮
- add_action('media_buttons', 'add_my_media_button');
- function add_my_media_button() {
- echo '<input id="boxmoe_up_img" type="file" accept="image/*" multiple="multiple"/>
- <label for="boxmoe_up_img" id="up_img_label" class="button"> 上传图片到图床</label>
- ';
- ?>
- <style type="text/css">
- #boxmoe_up_img {display: none;}
- #up_img_label:before {font-family: dashicons;content: "\f128";}
- </style>
- <script type="text/javascript">
- jQuery('#boxmoe_up_img').change(function() {
- window.wpActiveEditor = null;
- for (var i = 0; i < this.files.length; i++) {
- var f=this.files[i];
- if (!/image\/\w+/.test(f.type)) {
- alert('请选择图片文件(png | jpg | gif)');
- return
- }
- var formData=new FormData();
- formData.append('pic',f); //boxmoe提示:这里的pic就是api的post参数要修改的地方
- jQuery.ajax({
- async:true,
- crossDomain:true,
- url:'https://api.jsmoe.com/upimg/up.php', //boxmoe提示:这里就是api的地址,也就是上传接口
- type : 'POST',
- processData : false,
- contentType : false,
- dataType: 'json',
- data:formData,
- beforeSend: function (xhr) {
- jQuery('#up_img_label').html('<i class="fa fa-spinner rotating" aria-hidden="true"></i> Uploading...');
- },
- success:function(res){
- wp.media.editor.insert('<a href='+ res.data.url +'><img src='+ res.data.url +' ></img></a>'); //boxmoe提示:res.data.url 这里的url就是返回的参数
- jQuery("#up_img_label").html('<i class="fa fa-check" aria-hidden="true"></i> 上传成功,继续上传');
- },
- error: function (){
- jQuery("#up_img_label").html('<i class="fa fa-times" aria-hidden="true"></i> 上传失败,重新上传');
- }
- });
- }
- });
- </script>
- <?php
- }
如果是自建接口,但是存在跨域问题,则需要在图床上添加主机头
复制代码
- header('Access-Control-Allow-Origin: https://www.boxmoe.com'); //boxmoe提示:域名改成你的博客域名
- header('Access-Control-Allow-Methods: POST');
- header('Access-Control-Allow-Headers: Content-Type, Accept, Authorization, X-Requested-With, Origin, Accept');
评论(16)