#教程# WordPress – 编辑器添加按钮 用API上传到Chevereto图床

前言

前段时间搭建了Chevereto图床,但在 WordPress 编辑器里需要上传图片的时候,需要另外打开图床上传比较麻烦。这时候可以在 WordPress 的编辑器里添加个上传按钮,利用 API 上传到Chevereto图床,这样上传图片到图床就方便啦!

图片[1] - #教程# WordPress – 编辑器添加按钮 用API上传到Chevereto图床 - 云线路

添加方法

修改 Chevereto

获取 API KEY: 登录,转到仪表盘-设置-API,将 API v1 key 记录下来;

API 后端设置: 进入 Chevereto 的安装目录,将 app/routes/route.api.php 文件拷贝到 app/routes/overrides/route.api.php 文件;

允许跨域: 打开 app/routes/overrides/route.api.php,添加

header('Access-Control-Allow-Origin: https://www.yunloc.com');
header('Access-Control-Allow-Methods: POST');
header('Access-Control-Allow-Headers: Content-Type, Accept, Authorization, X-Requested-With, Origin, Accept');

记得把白名单 https://www.yunloc.com 改成自己的域名或者改成* (所有域名可用);

设置 API user(可选): 在 app/routes/overrides/route.api.php 中,找到$uploaded_id = CHV\Image::uploadToWebsite($source);那一行,更改为

$uploaded_id = CHV\Image::uploadToWebsite($source,admin);

将 admin 替换为图床中的用户;

修改 WordPress

前端添加上传按钮(media button): 将以下代码添加到WordPress正在使用的主题目录的 functions.php 中

//添加图床上传按钮
add_action('media_buttons', 'add_my_media_button');
function add_my_media_button() {
    $currentUser = wp_get_current_user();
        if(!empty($currentUser->roles) && in_array('administrator', $currentUser->roles)){
            $DOMAIN="图床的域名 例:img.7198.net";
            $APIkey="图床的 API v1 key";// 是管理员
        }
        else
            return 0;  // 非管理员
    echo '
            <input id="up_to_chevereto" type="file" accept="image/*" multiple="multiple"/>
            <label for="up_to_chevereto" id="up_img_label"><i class="fa fa-picture-o" aria-hidden="true"></i> 上传图片到 Chevereto</label>
          ';
?>
<style type="text/css">
#up_to_chevereto {
  display: none;
}
#up_img_label {
  color: #fff;
  background-color: #16a085;
  border-radius: 5px;
  display: inline-block;
  padding: 5.2px;
}
</style>
<script type="text/javascript">
$('#up_to_chevereto').change(function() {
  window.wpActiveEditor = null;
  for (var i = 0; i < this.files.length; i++) {
    var f=this.files[i];
    var formData=new FormData();
    formData.append('source',f);
    $.ajax({
        async:true,
        crossDomain:true,
        url:'https://<?php echo $DOMAIN; ?>/api/1/upload/?key=<?php echo $APIkey; ?>&format=json',
        type : 'POST',
        processData : false,
        contentType : false,
        data:formData,
        beforeSend: function (xhr) {
            $('#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.image.url+'><img src='+res.image.url+' alt='+res.image.title+'></img></a>');
            $("#up_img_label").html('<i class="fa fa-check" aria-hidden="true"></i> 上传成功,继续上传');
        },
        error: function (){
            $("#up_img_label").html('<i class="fa fa-times" aria-hidden="true"></i> 上传失败,重新上传');
        }
    });
  }
});
</script>
<?php
}

2019/12/16 更新

上传有问题,主要是 https 混用和 CORS 的问题,故在这里更新上传方法,上传方式改用 WordPress REST API,为了保证兼容,请确保 WordPress 版本为 4.9+。注意:前文的操作均不用管,以下的操作均在 functions.php 中完成。

注册路由

add_action('rest_api_init', function () {
    register_rest_route('chevereto/v1', '/image/upload', array(
        'methods' => 'POST',
        'callback' => 'upload_to_chevereto',
    ));
});

之后,可以使用 post 的方式发送数据到 http(s)://博客域名/chevereto/v1/image/upload 来上传图片。

加入回调函数

function upload_to_chevereto() {
    //Authentication
    if (!check_ajax_referer('wp_rest', '_wpnonce', false)) {
        $output = array('status' => 403,
            'message' => 'Unauthorized client.',
            'link' => $link,
        );
        $result = new WP_REST_Response($output, 403);
        $result->set_headers(array('Content-Type' => 'application/json'));
        return $result;
    }
    $image = file_get_contents($_FILES["chevereto_img_file"]["tmp_name"]);
    $upload_url = '图床的域名/api/1/upload';
    $args = array(
        'body' => array(
            'source' => base64_encode($image),
            'key' => '图床的 API v1 key',
        ),
    );

    $response = wp_remote_post($upload_url, $args);
    $reply = json_decode($response["body"]);

    if ($reply->status_txt == 'OK' && $reply->status_code == 200) {
        $status = 200;
        $message = "success";
        $link = $reply->image->image->url;
    } else {
        $status = $reply->status_code;
        $message = $reply->error->message;
        $link = $link;
    }
    $output = array(
        'status' => $status,
        'message' => $message,
        'link' => $link,
    );
    $result = new WP_REST_Response($output, $status);
    $result->set_headers(array('Content-Type' => 'application/json'));
    return $result;
}

将图床的域名和图床的 API v1 key 填写完整,注意加上 http 或 https

后台编辑器添加按钮

//添加图床上传按钮
add_action('media_buttons', 'add_my_media_button');
function add_my_media_button() {
    echo '
            <input id="up_to_chevereto" type="file" accept="image/*" multiple="multiple"/>
            <label for="up_to_chevereto" id="up_img_label"><i class="fa fa-picture-o" aria-hidden="true"></i> 上传图片到 Chevereto</label>
          ';
?>
<style type="text/css">
#up_to_chevereto {
  display: none;
}
#up_img_label {
  color: #fff;
  background-color: #16a085;
  border-radius: 5px;
  display: inline-block;
  padding: 5.2px;
}
</style>
<script type="text/javascript">
jQuery('#up_to_chevereto').change(function() {
  window.wpActiveEditor = null;
  for (var i = 0; i < this.files.length; i++) {
    var f=this.files[i];
    var formData=new FormData();
    formData.append('chevereto_img_file',f);
    jQuery.ajax({
        async:true,
        crossDomain:true,
        url:'<?php echo rest_url("chevereto/v1/image/upload") ."?_wpnonce=". wp_create_nonce("wp_rest"); ?>',
        type : 'POST',
        processData : false,
        contentType : false,
        data:formData,
        beforeSend: function () {
            jQuery('#up_img_label').html('<i class="fa fa-spinner rotating" aria-hidden="true"></i> Uploading...');
        },
        success:function(res){
            if (res.status == 200) {
                wp.media.editor.insert('<a href="'+res.link+'"><img src="'+res.link+'" alt="'+f.name+'"></img></a>');
                jQuery("#up_img_label").html('<i class="fa fa-check" aria-hidden="true"></i> 上传成功,继续上传');
            }else{
                console.log("code: "+res.status+"message: "+res.message);
            }
        },
        error: function (){
            jQuery("#up_img_label").html('<i class="fa fa-times" aria-hidden="true"></i> 上传失败,重新上传');
        }
    });
  }
});
</script>
<?php
}

结语

好啦,到这里就结束了,本文内容参考自spiritx版权所有。本站文章可自由引用,但请注明来源。

© 本站文章随意转载,但请注明出处!
THE END
点赞2W+ 分享
评论 抢沙发
头像
务必使用真实的邮箱地址评论,虚假邮箱的评论将不通过审核及无回复。
提交
头像

昵称

取消
昵称表情代码图片

    暂无评论内容