在当前主题的functions.php文件最下面添加以下代码:
//添加图床上传按钮 add_action('media_buttons', 'add_my_media_button'); function add_my_media_button() { echo '<input id="karma617_up_img" type="file" accept="image/*" multiple="multiple"/> <label for="karma617_up_img" id="up_img_label" class="button"> 上传图片到图床</label> '; ?> <style type="text/css"> #karma617_up_img { display: none; } #up_img_label:before { font-family: dashicons; content: "\f128"; } </style> <script type="text/javascript"> jQuery('#karma617_up_img').off("change").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('images', f); //提示:这里的images是api的文件请求参数名 jQuery.ajax({ async: true, crossDomain: true, url: 'xxxxx', //提示:这里是上传接口地址 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) { console.log(res.data.imageURLs[0]) wp.media.editor.insert('<a href=' + res.data.url + '><img src=' + res.data.url + ' ></img></a>'); //提示: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 }