当前位置:首页文章笔记建站教程WordPress 如何在前端添加一个wp_editor编辑器带图片上传却不弹出媒体库

WordPress 如何在前端添加一个wp_editor编辑器带图片上传却不弹出媒体库

在我们 WordPress 开发中经常会遇到编辑器的问题,wordpress 自带有个编辑器 wp_editor,编辑器有上传图片功能,但是是需要添加到媒体且需要弹出媒体库的窗口,这样对于在前台投稿的用户来说可能不太友好。那么我们如何能在前台添加一个极简且带图片上传的编辑器呢?这里模板兔给大家讲解一下。

首先调用编辑器,我们需要对编辑器上面的按钮简化一下。

  1. wp_editor( , ‘task_content’, task_editor_settings(array(‘textarea_name’=>‘content’, ‘height’=>250, ‘allow_img’=> 1)) );

然后我们定义一些函数以及处理上传的逻辑

  1. function task_editor_settings($args = array()){
  2. $allow_img = isset($args[‘allow_img’]) && $args[‘allow_img’] ? 1 : 0;
  3. return array(
  4. ‘textarea_name’ => $args[‘textarea_name’],
  5. ‘media_buttons’ => false,
  6. ‘quicktags’ => false,
  7. ‘tinymce’ => array(
  8. ‘statusbar’ => false,
  9. ‘height’ => isset($args[‘height’]) ? $args[‘height’] : 120,
  10. ‘toolbar1’ => ‘bold,italic,underline,blockquote,bullist,numlist’.($allow_img?‘,TaskImg’:),
  11. ‘toolbar2’ => ,
  12. ‘toolbar3’ =>
  13. )
  14. );
  15. }
  16. add_filter( ‘mce_external_plugins’, ‘erphp_task_mce_plugin’);
  17. function erphp_task_mce_plugin($plugin_array){
  18. $plugin_array[‘TaskImg’] = ERPHP_TASK_URL . ‘/static/js/TaskImg.js’;
  19. return $plugin_array;
  20. }
  21. add_action(‘wp_ajax_task_img_upload’, ‘erphp_task_img_upload’);
  22. function erphp_task_img_upload(){
  23. $res = array();
  24. $user = wp_get_current_user();
  25. if($user->ID){
  26. $upfile = $_FILES[‘upfile’];
  27. $upload_overrides = array(‘test_form’ => false);
  28. $file_return = wp_handle_upload($upfile, $upload_overrides);
  29. if ($file_return && !isset($file_return[‘error’])) {
  30. // 保存到媒体库
  31. $attachment = array(
  32. ‘post_title’ => preg_replace( ‘/\.[^.]+$/’, , basename( $file_return[‘file’] ) ),
  33. ‘post_mime_type’ => $file_return[‘type’],
  34. );
  35. $attach_id = wp_insert_attachment($attachment, $file_return[‘file’]);
  36. $attach_data = generate_attachment_metadata($attach_id, $file_return[‘file’]);
  37. wp_update_attachment_metadata($attach_id, $attach_data);
  38. $res[‘result’] = 0;
  39. $file_return[‘alt’] = preg_replace( ‘/\.[^.]+$/’, , basename( $file_return[‘file’] ) );
  40. $res[‘image’] = $file_return;
  41. } else {
  42. $res[‘result’] = 1;
  43. }
  44. } else {
  45. $res[‘result’] = 2;
  46. }
  47. echo json_encode($res);
  48. exit;
  49. }
  50. function generate_attachment_metadata($attachment_id, $file) {
  51. $attachment = get_post ( $attachment_id );
  52. $metadata = array ();
  53. if (!function_exists(‘file_is_displayable_image’)) include( ABSPATH . ‘wp-admin/includes/image.php’ );
  54. if (preg_match ( ‘!^image/!’, get_post_mime_type ( $attachment ) ) && file_is_displayable_image ( $file )) {
  55. $imagesize = getimagesize ( $file );
  56. $metadata [‘width’] = $imagesize [0];
  57. $metadata [‘height’] = $imagesize [1];
  58. list ( $uwidth, $uheight ) = wp_constrain_dimensions ( $metadata [‘width’], $metadata [‘height’], 128, 96 );
  59. $metadata [‘hwstring_small’] = "height=’$uheight‘ width=’$uwidth‘";
  60. // Make the file path relative to the upload dir
  61. $metadata [‘file’] = _wp_relative_upload_path ( $file );
  62. // work with some watermark plugin
  63. $metadata = apply_filters ( ‘wp_generate_attachment_metadata’, $metadata, $attachment_id );
  64. }
  65. return $metadata;
  66. }

然后需要 js 来实现上传

  1. tinymce.PluginManager.add(‘TaskImg’, function(editor, url) {
  2. var $el = jQuery(editor.getElement()).parent();
  3. var timer = null;
  4. var input = document.createElement(‘input’);
  5. input.setAttribute(‘type’, ‘file’);
  6. input.setAttribute(‘accept’, ‘image/*’);
  7. function notice(type, msg, time){
  8. clearTimeout(timer);
  9. jQuery(‘#notice’).remove();
  10. $el.append(‘<div id="notice"><div class="notice-bg"></div><div class="notice-wrap"><div class="notice-inner notice-‘+type+‘">’+msg+‘</div></div></div>’);
  11. if(time) {
  12. timer = setTimeout(function () {
  13. jQuery(‘#notice’).remove();
  14. }, time);
  15. }
  16. }
  17. function img_post() {
  18. var fd = new FormData();
  19. fd.append( "upfile", input.files[0]);
  20. fd.append( "action", ‘task_img_upload’);
  21. jQuery.ajax({
  22. type: ‘POST’,
  23. url: _ERPHP.ajaxurl,
  24. data: fd,
  25. processData: false,
  26. contentType: false,
  27. dataType: ‘json’,
  28. success: function(data, textStatus, XMLHttpRequest) {
  29. clearTimeout(timer);
  30. jQuery(‘#notice’).remove();
  31. if(data.result==‘0’){
  32. editor.insertContent( ‘<img src="’+data.image.url+‘" alt="’+data.image.alt+‘">’ );
  33. }else{
  34. notice(0, ‘图片上传出错,请稍后再试!’, 1200);
  35. }
  36. },
  37. error: function(MLHttpRequest, textStatus, errorThrown) {
  38. clearTimeout(timer);
  39. jQuery(‘#notice’).remove();
  40. alert(errorThrown);
  41. }
  42. });
  43. }
  44. input.onchange = function() {
  45. var file = this.files[0];
  46. if(file){
  47. if(!/\.(gif|jpg|jpeg|png|GIF|JPG|JPEG|PNG)$/.test(file.name)){
  48. notice(0, ‘仅支持上传jpg、png、gif格式的图片文件’, 2000);
  49. return false;
  50. }else if(file.size > 2 * 1024 * 1024){
  51. notice(0, ‘图片大小不能超过2M’, 1500);
  52. return false;
  53. }else{
  54. img_post();
  55. notice(1, ‘正在上传…’, 0);
  56. }
  57. }
  58. };
  59. editor.addButton(‘TaskImg’, {
  60. text: ,
  61. icon: ‘image’,
  62. tooltip: "上传图片",
  63. classes: ‘TaskImg’,
  64. onclick: function() {
  65. if( ! /Android|webOS|iPhone|iPod|BlackBerry/i.test(navigator.userAgent) ) {
  66. input.click();
  67. }
  68. },
  69. onTouchEnd: function(){
  70. if( /Android|webOS|iPhone|iPod|BlackBerry/i.test(navigator.userAgent) ) {
  71. input.click();
  72. }
  73. }
  74. });
  75. });

最后需要说明一点的是,用户需要具备 wordpress 的上传权限。

教程比较初略,需要具备一定开发能力的人方可了解清楚~

温馨提示:

文章标题:WordPress 如何在前端添加一个wp_editor编辑器带图片上传却不弹出媒体库

文章链接:https://www.wuyanshuo.cn/1301.html

更新时间:2022年09月12日

本站大部分内容均收集于网络!若内容若侵犯到您的权益,请发送邮件至:service@wuyanshuo.cn我们将第一时间处理! 资源所需价格并非资源售卖价格,是收集、整理、编辑详情以及本站运营的适当补贴,并且本站不提供任何免费技术支持。 所有资源仅限于参考和学习,版权归原作者所有,更多请阅读无言说网络服务协议

给TA打赏
共{{data.count}}人
人已打赏
建站教程

如何实现WordPress搜索结果显示指定的文章分类

2022-9-12 10:58:41

建站教程

jQuery获取url并替换url参数(有则替换,没有则增加)

2022-9-12 16:58:19

0 条回复 A文章作者 M管理员
    暂无讨论,说说你的看法吧
个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索
'