WordPress教程

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.  
  17. add_filter( 'mce_external_plugins', 'erphp_task_mce_plugin');
  18. function erphp_task_mce_plugin($plugin_array){
  19. $plugin_array['TaskImg'] = ERPHP_TASK_URL . '/static/js/TaskImg.js';
  20. return $plugin_array;
  21. }
  22.  
  23. add_action('wp_ajax_task_img_upload', 'erphp_task_img_upload');
  24. function erphp_task_img_upload(){
  25. $res = array();
  26.  
  27. $user = wp_get_current_user();
  28. if($user->ID){
  29. $upfile = $_FILES['upfile'];
  30. $upload_overrides = array('test_form' => false);
  31. $file_return = wp_handle_upload($upfile, $upload_overrides);
  32.  
  33. if ($file_return && !isset($file_return['error'])) {
  34. // 保存到媒体库
  35. $attachment = array(
  36. 'post_title' => preg_replace( '/\.[^.]+$/', '', basename( $file_return['file'] ) ),
  37. 'post_mime_type' => $file_return['type'],
  38. );
  39. $attach_id = wp_insert_attachment($attachment, $file_return['file']);
  40. $attach_data = generate_attachment_metadata($attach_id, $file_return['file']);
  41. wp_update_attachment_metadata($attach_id, $attach_data);
  42. $res['result'] = 0;
  43. $file_return['alt'] = preg_replace( '/\.[^.]+$/', '', basename( $file_return['file'] ) );
  44. $res['image'] = $file_return;
  45. } else {
  46. $res['result'] = 1;
  47. }
  48. } else {
  49. $res['result'] = 2;
  50. }
  51. echo json_encode($res);
  52. exit;
  53. }
  54.  
  55. function generate_attachment_metadata($attachment_id, $file) {
  56. $attachment = get_post ( $attachment_id );
  57. $metadata = array ();
  58. if (!function_exists('file_is_displayable_image')) include( ABSPATH . 'wp-admin/includes/image.php' );
  59.  
  60. if (preg_match ( '!^image/!', get_post_mime_type ( $attachment ) ) && file_is_displayable_image ( $file )) {
  61. $imagesize = getimagesize ( $file );
  62. $metadata ['width'] = $imagesize [0];
  63. $metadata ['height'] = $imagesize [1];
  64. list ( $uwidth, $uheight ) = wp_constrain_dimensions ( $metadata ['width'], $metadata ['height'], 128, 96 );
  65. $metadata ['hwstring_small'] = "height='$uheight' width='$uwidth'";
  66.  
  67. // Make the file path relative to the upload dir
  68. $metadata ['file'] = _wp_relative_upload_path ( $file );
  69. // work with some watermark plugin
  70. $metadata = apply_filters ( 'wp_generate_attachment_metadata', $metadata, $attachment_id );
  71. }
  72. return $metadata;
  73. }

然后需要 js 来实现上传

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

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

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

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

已有 264 人购买
查看演示升级 VIP立刻购买

收藏
(1)

发表回复

热销模板

Ashade - 作品展示摄影相册WordPress汉化主题
LensNews

本站承接 WordPress / PbootCMS / DedeCMS 等
系统建站、仿站、开发、定制等业务!