建站教程

建站教程

Products

当前位置:首页 > 建站教程 >

如何在不弹出WordPress中的媒体库的情况下通过图像上传将wp_editor编辑器添加到前端

GG网络技术分享 2025-03-18 16:12 0


在我们的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的上传权限。

教程比较简短,只有有一定开发能力的人才看得清楚~

标签: WordPress op

提交需求或反馈

Demand feedback