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

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

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

在我们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="https://www.mobantu.com/9340.html'+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的上传权限。

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

原文链接:https://www.dqzy.cn/2025/04/18/403.html,转载请注明出处。 1、本站所有源码资源(包括源代码、软件、学习资料等)仅供研究学习以及参考等合法使用,请勿用于商业用途以及违法使用。如本站不慎侵犯您的版权请联系我们,我们将及时处理,并撤下相关内容! 2、访问本站的用户必须明白,本站对所提供下载的软件和程序代码不拥有任何权利,其版权归该软件和程序代码的合法拥有者所有,请用户在下载使用前必须详细阅读并遵守软件作者的“使用许可协议”,本站仅仅是一个学习交流的平台。 3、如下载的压缩包需要解压密码,若无特殊说明,那么文件的解压密码则为:www.dqzy.cn。 4、点启资源网是一个免费且专业分享网站源码、图片素材、特效代码、教程文章、站长工具的平台。我们努力给站长提供好的资源!
0

评论0

请先
显示验证码
没有账号?注册  忘记密码?