WordPress编辑器中添加“上传到Chevereto图床”

建站4年前 (2021)更新 刘丰源
10,647 0 0

效果图:

WordPress编辑器中添加“上传到Chevereto图床”
支持多张图片上传

获取API Key

准备一个Chevereto搭建的图床,转到仪表盘-设置-API,将API v1 key记录下来,一会儿要用

API后端设置

进入Chevereto的安装目录,将app/routes/route.api.php文件拷贝到app/routes/overrides/route.api.php文件

允许跨域

打开app/routes/overrides/route.api.php,第二行(<?php后面)添加如下几行

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

app/routes/overrides/route.api.php中,找到

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

那一行,更改为

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

spirit替换为图床中的用户

前端添加上传按钮(media button)

将以下代码添加到WordPress正在使用的主题目录的functions.php中(不能直接在主题编辑器中添加,需要通过sftp方式或者其他直接修改文件才可以)

//添加图床上传按钮
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="图床的域名";
            $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">
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('source',f);
    jQuery.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) {
            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.image.url+'"><img src="'+res.image.url+'" alt="'+res.image.title+'"></img></a>');
            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
}

style里的样式可以根据自己偏好自定义

这里我的编辑器用的是WP Editor.md,界面不同但不影响上传按钮的使用
WordPress编辑器中添加“上传到Chevereto图床”

© 版权声明

相关文章

暂无评论

暂无评论...