乐云主机笔记

  • 首页
  • 主机优惠
  • 学习记录
  • 新手教程
  • 自用主机
  • 资源下载
  • 网赚项目
  • 每天20分
乐尚云端
关注主机信息、建站技术的资深小白~白
  1. 首页
  2. 学习记录
  3. 正文

WordPress 主题 编辑器中添加上传到 Chevereto图床

2021年1月10日 131点热度 0人点赞 0条评论

Chevereto 国外知名图床系统。对于闲置VPS,我们可以选择做为博客论坛的图床使用。更新发布文章也会使用图床,上传复制链接步骤有点繁琐。在Chevereto的仪表发现了API V1后,一切变得将会简单起来。

先上一张成果图:

WordPress 主题 编辑器中添加上传到 Chevereto图床第1张

tip:支持多张图片上传哦!

获取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后面)添加如下几行

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

记得把白名单https://*.lurending.com改成自己的域名或者改成*

设置API user(可选)

在app/routes/overrides/route.api.php中,找到$uploaded_id = CHVImage::uploadToWebsite($source);那一行,更改为

$uploaded_id = CHVImage::uploadToWebsite($source,spirit);

将spirit替换为图床中的用户

前端添加上传按钮(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="图床的域名";
            $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图床第2张

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
}

至此结束。

参考:https://spiritx.xyz/843.html

转载:https://www.lurending.com/1284.html

标签: 暂无
最后更新:2021年1月10日

LetVps

关注建站主机信息及技术的资深小白白~

点赞
< 上一篇
下一篇 >

文章评论

取消回复

主机商推荐

最新 热点 随机
最新 热点 随机
腾讯云轻量服务器 DD windows 甲骨文oraclecloud 免费机 DD安装成Windows系统 保姆级教程 百分百成功! Linux VPS安装Fikkerd 3.7.6全功能破解版 附使用指南 hosthatch大盘+ 小盘组内网教程 分享一款开源WordPress主题CorePress,可以博客/CMS 帝国CMS仿线报资源网整站模版下载[转载] 利用nginx+php反代宝塔官网来实现开心版 B2+CF+ShareX,实现无成本图床和便捷上传
解决wordpress无法建立目录 uploads/年/月份。有没有上级目录的写权限?介绍两款端口转发面板(咸蛋面板、极光面板)分享一款开源WordPress主题CorePress,可以博客/CMS火车头采集器zblog-PHP发布接口下载及配置教程利用VPS/服务器搭建FRP服务,实现内外网互通Linux修改默认cubic拥塞算法,启用tcp_hybla,加速网络使用 Backblaze B2 和 Cloudflare Workers 搭建免费的自定义域名图床|转载B2+CF+ShareX,实现无成本图床和便捷上传
利用Openload和FTP备份脚本0成本自动备份VPS 一款开源多用户网盘系统(蓝眼云盘) WordPress终极简码插件shortcodes ultimate 快速100+短代码 火狐浏览器油猴子GreaseMonkey使用教程 [最新测试]宝塔BT-PANEL下反代discuz论坛并实现登陆、发帖、管理功能 ysfaka大佬分享的新发卡系统收藏备用 #网赚教程# Ebesucher挂机赚钱教程之(一) 好用在线文件管理器KODExplorer放出新版本。
主机商推荐

书签
  • 猫云云计算

COPYRIGHT © 2020 乐云主机笔记. ALL RIGHTS RESERVED.

THEME KRATOS MADE BY VTROIS

粤ICP备15031609号-3