记录一些常用的函数和瞎折腾的过程……

wordpress后台编辑器调用api增加图片上传功能

提醒:本文最后更新于 897 天前,文中所描述的信息可能已发生改变,请谨慎使用。

如果你的wordpress中的图片是分离的,比如说有个单独的图床,并且可以调用api的话,那么可以用下面的代码实现在wordpress后台编辑器直接调用api,上传图片到你的图床。这样省去了到图床上传图片麻烦。

代码来自:盒子萌

具体效果如下图:

后台编辑器上传图片按钮

<?php
//添加图床上传按钮
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('image',f); //这里的image就是api的post参数要修改的地方
      jQuery.ajax({
        async:true,
        crossDomain:true,
        url:'https://api.images.com/upload', //这里就是api的地址,也就是上传接口
        headers : {"token" : "your token"}, //如果需要在header中token认证的话
        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
}