在我们 WordPress 开发中经常会遇到编辑器的问题,wordpress 自带有个编辑器 wp_editor,编辑器有上传图片功能,但是是需要添加到媒体且需要弹出媒体库的窗口,这样对于在前台投稿的用户来说可能不太友好。那么我们如何能在前台添加一个极简且带图片上传的编辑器呢?这里给大家讲解一下。
首先调用编辑器,我们需要对编辑器上面的按钮简化一下。
- wp_editor( '', 'task_content', task_editor_settings(array('textarea_name'=>'content', 'height'=>250, 'allow_img'=> 1)) );
然后我们定义一些函数以及处理上传的逻辑
- function task_editor_settings($args = array()){
- $allow_img = isset($args['allow_img']) && $args['allow_img'] ? 1 : 0;
- return array(
- 'textarea_name' => $args['textarea_name'],
- 'media_buttons' => false,
- 'quicktags' => false,
- 'tinymce' => array(
- 'statusbar' => false,
- 'height' => isset($args['height']) ? $args['height'] : 120,
- 'toolbar1' => 'bold,italic,underline,blockquote,bullist,numlist'.($allow_img?',TaskImg':''),
- 'toolbar2' => '',
- 'toolbar3' => ''
- )
- );
- }
- add_filter( 'mce_external_plugins', 'erphp_task_mce_plugin');
- function erphp_task_mce_plugin($plugin_array){
- $plugin_array['TaskImg'] = ERPHP_TASK_URL . '/static/js/TaskImg.js';
- return $plugin_array;
- }
- add_action('wp_ajax_task_img_upload', 'erphp_task_img_upload');
- function erphp_task_img_upload(){
- $res = array();
- $user = wp_get_current_user();
- if($user->ID){
- $upfile = $_FILES['upfile'];
- $upload_overrides = array('test_form' => false);
- $file_return = wp_handle_upload($upfile, $upload_overrides);
- if ($file_return && !isset($file_return['error'])) {
- // 保存到媒体库
- $attachment = array(
- 'post_title' => preg_replace( '/\.[^.]+$/', '', basename( $file_return['file'] ) ),
- 'post_mime_type' => $file_return['type'],
- );
- $attach_id = wp_insert_attachment($attachment, $file_return['file']);
- $attach_data = generate_attachment_metadata($attach_id, $file_return['file']);
- wp_update_attachment_metadata($attach_id, $attach_data);
- $res['result'] = 0;
- $file_return['alt'] = preg_replace( '/\.[^.]+$/', '', basename( $file_return['file'] ) );
- $res['image'] = $file_return;
- } else {
- $res['result'] = 1;
- }
- } else {
- $res['result'] = 2;
- }
- echo json_encode($res);
- exit;
- }
- function generate_attachment_metadata($attachment_id, $file) {
- $attachment = get_post ( $attachment_id );
- $metadata = array ();
- if (!function_exists('file_is_displayable_image')) include( ABSPATH . 'wp-admin/includes/image.php' );
- if (preg_match ( '!^image/!', get_post_mime_type ( $attachment ) ) && file_is_displayable_image ( $file )) {
- $imagesize = getimagesize ( $file );
- $metadata ['width'] = $imagesize [0];
- $metadata ['height'] = $imagesize [1];
- list ( $uwidth, $uheight ) = wp_constrain_dimensions ( $metadata ['width'], $metadata ['height'], 128, 96 );
- $metadata ['hwstring_small'] = "height='$uheight' width='$uwidth'";
- // Make the file path relative to the upload dir
- $metadata ['file'] = _wp_relative_upload_path ( $file );
- // work with some watermark plugin
- $metadata = apply_filters ( 'wp_generate_attachment_metadata', $metadata, $attachment_id );
- }
- return $metadata;
- }
然后需要 js 来实现上传
- tinymce.PluginManager.add('TaskImg', function(editor, url) {
- var $el = jQuery(editor.getElement()).parent();
- var timer = null;
- var input = document.createElement('input');
- input.setAttribute('type', 'file');
- input.setAttribute('accept', 'image/*');
- function notice(type, msg, time){
- clearTimeout(timer);
- jQuery('#notice').remove();
- $el.append('<div id="notice"><div class="notice-bg"></div><div class="notice-wrap"><div class="notice-inner notice-'+type+'">'+msg+'</div></div></div>');
- if(time) {
- timer = setTimeout(function () {
- jQuery('#notice').remove();
- }, time);
- }
- }
- function img_post() {
- var fd = new FormData();
- fd.append( "upfile", input.files[0]);
- fd.append( "action", 'task_img_upload');
- jQuery.ajax({
- type: 'POST',
- url: _ERPHP.ajaxurl,
- data: fd,
- processData: false,
- contentType: false,
- dataType: 'json',
- success: function(data, textStatus, XMLHttpRequest) {
- clearTimeout(timer);
- jQuery('#notice').remove();
- if(data.result=='0'){
- editor.insertContent( '<img src="'+data.image.url+'" alt="'+data.image.alt+'">' );
- }else{
- notice(0, '图片上传出错,请稍后再试!', 1200);
- }
- },
- error: function(MLHttpRequest, textStatus, errorThrown) {
- clearTimeout(timer);
- jQuery('#notice').remove();
- alert(errorThrown);
- }
- });
- }
- input.onchange = function() {
- var file = this.files[0];
- if(file){
- if(!/\.(gif|jpg|jpeg|png|GIF|JPG|JPEG|PNG)$/.test(file.name)){
- notice(0, '仅支持上传jpg、png、gif格式的图片文件', 2000);
- return false;
- }else if(file.size > 2 * 1024 * 1024){
- notice(0, '图片大小不能超过2M', 1500);
- return false;
- }else{
- img_post();
- notice(1, '正在上传...', 0);
- }
- }
- };
- editor.addButton('TaskImg', {
- text: '',
- icon: 'image',
- tooltip: "上传图片",
- classes: 'TaskImg',
- onclick: function() {
- if( ! /Android|webOS|iPhone|iPod|BlackBerry/i.test(navigator.userAgent) ) {
- input.click();
- }
- },
- onTouchEnd: function(){
- if( /Android|webOS|iPhone|iPod|BlackBerry/i.test(navigator.userAgent) ) {
- input.click();
- }
- }
- });
- });
最后需要说明一点的是,用户需要具备 wordpress 的上传权限。
教程比较初略,需要具备一定开发能力的人方可了解清楚~