WordPress编辑器中添加“上传到Chevereto图床”
🌶 过期警告: 本页面距今已有 1319 天未更新,年久失修,内容可能有所偏颇,还请仔细甄别!
缘由
之前我的图片是放在用oneindex搭建的网盘上,blog文章的图片存放在Onedrive上,同步至 oneindex,但似乎OneDrive的api接口对访问量有限制,有时我浏览博客的会发现图片不能 显示。
这样的情况持续了很久,直到我偶然了解到了 Chevereto ,于是决定搭建一个图床来存放图 片。
前段时间我把我博客文章的图片一张一张从OneDrive上转移到了Chevereto图床,虽然我的 图片不算太多,但这种在图床页面上传再回到博客文章编辑页面的方式浪费了我很多时间, 并且以后更新文章也会使用图床,我可不想这样一步步傻傻地操作。
在Chevereto的仪表发现了API V1后,我开始研究。网上关于这个的资料很少,作为一个小 白,我的探索之路很是艰辛。
先上一张成果图:
获取API KEY
- 准备一个
Chevereto
搭建的图床(废话!),不会搭建的话请Google
- 登录,转到
仪表盘-设置-API
,将API v1 key
记录下来,一会儿要用
API后端设置
进入Chevereto
的安装目录,将app/routes/route.api.php
文件拷贝 到app/routes/overrides/route.api.php
文件
允许跨域
打开app/routes/overrides/route.api.php
,第二行(<?php后面
)添加如下几行
1header('Access-Control-Allow-Origin: https://spiritx.xyz');2header('Access-Control-Allow-Methods: POST');3header('Access-Control-Allow-Headers: Content-Type, Accept, Authorization, X-Requested-With, Origin, Accept');
记得把白名单https://spiritx.xyz
改成自己的域名或者改成*
设置API user(可选)
在app/routes/overrides/route.api.php
中,找到
1$uploaded_id = CHV\Image::uploadToWebsite($source);
那一行,更改为
1$uploaded_id = CHV\Image::uploadToWebsite($source,spirit);
将spirit
替换为图床中的用户
前端添加上传按钮(media button)
将以下代码添加到WordPress
正在使用的主题目录的functions.php
中
1//添加图床上传按钮2add_action('media_buttons', 'add_my_media_button');3function add_my_media_button() {4 $currentUser = wp_get_current_user();5 if(!empty($currentUser->roles) && in_array('administrator', $currentUser->roles)){6 $DOMAIN="图床的域名";7 $APIkey="图床的API v1 key";// 是管理员8 }9 else10 return 0; // 非管理员11 echo '12 <input id="up_to_chevereto" type="file" accept="image/*" multiple="multiple"/>13 <label for="up_to_chevereto" id="up_img_label"><i class="fa fa-picture-o" aria-hidden="true"></i> 上传图片到Chevereto</label>14 ';15?>44 collapsed lines
16<style type="text/css">17#up_to_chevereto {18 display: none;19}20#up_img_label {21 color: #fff;22 background-color: #16a085;23 border-radius: 5px;24 display: inline-block;25 padding: 5.2px;26}27</style>28<script type="text/javascript">29jQuery('#up_to_chevereto').change(function() {30 window.wpActiveEditor = null;31 for (var i = 0; i < this.files.length; i++) {32 var f=this.files[i];33 var formData=new FormData();34 formData.append('source',f);35 jQuery.ajax({36 async:true,37 crossDomain:true,38 image:39 url:'https://<?php echo $DOMAIN; ?>/api/1/upload/?key=<?php echo $APIkey; ?>&format=json',40 type : 'POST',41 processData : false,42 contentType : false,43 data:formData,44 beforeSend: function (xhr) {45 jQuery('#up_img_label').html('<i class="fa fa-spinner rotating" aria-hidden="true"></i> Uploading...');46 },47 success:function(res){48 wp.media.editor.insert('<a href="'+res.image.url+'"><img src="'+res.image.url+'" alt="'+res.image.title+'"></img></a>');49 jQuery("#up_img_label").html('<i class="fa fa-check" aria-hidden="true"></i> 上传成功,继续上传');50 },51 error: function (){52 jQuery("#up_img_label").html('<i class="fa fa-times" aria-hidden="true"></i> 上传失败,重新上传');53 }54 });55 }56});57</script>58<?php59}
style
里的样式可以根据自己偏好自定义
使用预览
这里我的编辑器用的是WP Editor.md
,界面不同但不影响上传按钮的使用
更新
有几个小伙伴反馈说上传有问题,了解情况后主要是https
混用和CORS
的问题,故在这
里更新上传方法,上传方式改用WordPress REST API
,为了保证兼容,请确
保WordPress
版本为4.9+
。注意:前文的操作均不用管,以下的操作均在
functions.php
中完成。
注册路由
1add_action('rest_api_init', function () {2 register_rest_route('chevereto/v1', '/image/upload', array(3 'methods' => 'POST',4 'callback' => 'upload_to_chevereto',5 ));6});
之后,可以使用post
的方式发送数据到
http(s)://博客域名/chevereto/v1/image/upload
来上传图片。
加入回调函数
1function upload_to_chevereto() {2 //Authentication3 if (!check_ajax_referer('wp_rest', '_wpnonce', false)) {4 $output = array('status' => 403,5 'message' => 'Unauthorized client.',6 'link' => $link,7 );8 $result = new WP_REST_Response($output, 403);9 $result->set_headers(array('Content-Type' => 'application/json'));10 return $result;11 }12 $image = file_get_contents($_FILES["chevereto_img_file"]["tmp_name"]);13 $upload_url = '图床的域名/api/1/upload';14 $args = array(15 'body' => array(26 collapsed lines
16 'source' => base64_encode($image),17 'key' => '图床的API v1 key',18 ),19 );20
21 $response = wp_remote_post($upload_url, $args);22 $reply = json_decode($response["body"]);23
24 if ($reply->status_txt == 'OK' && $reply->status_code == 200) {25 $status = 200;26 $message = "success";27 $link = $reply->image->image->url;28 } else {29 $status = $reply->status_code;30 $message = $reply->error->message;31 $link = $link;32 }33 $output = array(34 'status' => $status,35 'message' => $message,36 'link' => $link,37 );38 $result = new WP_REST_Response($output, $status);39 $result->set_headers(array('Content-Type' => 'application/json'));40 return $result;41}
将图床的域名和图床的API v1 key
填写完整,注意加上http或https
后台编辑器添加按钮
1//添加图床上传按钮2add_action('media_buttons', 'add_my_media_button');3function add_my_media_button() {4 echo '5 <input id="up_to_chevereto" type="file" accept="image/*" multiple="multiple"/>6 <label for="up_to_chevereto" id="up_img_label"><i class="fa fa-picture-o" aria-hidden="true"></i> 上传图片到Chevereto</label>7 ';8?>9<style type="text/css">10#up_to_chevereto {11 display: none;12}13#up_img_label {14 color: #fff;15 background-color: #16a085;41 collapsed lines
16 border-radius: 5px;17 display: inline-block;18 padding: 5.2px;19}20</style>21<script type="text/javascript">22jQuery('#up_to_chevereto').change(function() {23 window.wpActiveEditor = null;24 for (var i = 0; i < this.files.length; i++) {25 var f=this.files[i];26 var formData=new FormData();27 formData.append('chevereto_img_file',f);28 jQuery.ajax({29 async:true,30 crossDomain:true,31 image:32 url:'<?php echo rest_url("chevereto/v1/image/upload") ."?_wpnonce=". wp_create_nonce("wp_rest"); ?>',33 type : 'POST',34 processData : false,35 contentType : false,36 data:formData,37 beforeSend: function () {38 jQuery('#up_img_label').html('<i class="fa fa-spinner rotating" aria-hidden="true"></i> Uploading...');39 },40 success:function(res){41 if (res.status == 200) {42 wp.media.editor.insert('<a href="'+res.link+'"><img src="'+res.link+'" alt="'+f.name+'"></img></a>');43 jQuery("#up_img_label").html('<i class="fa fa-check" aria-hidden="true"></i> 上传成功,继续上传');44 }else{45 console.log("code: "+res.status+"message: "+res.message);46 }47 },48 error: function (){49 jQuery("#up_img_label").html('<i class="fa fa-times" aria-hidden="true"></i> 上传失败,重新上传');50 }51 });52 }53});54</script>55<?php56}
然后就开始使用吧 :smile: