<?php
// WordPress environment
require( dirname(__FILE__) . '/../../../wp-load.php' );
$wordpress_upload_dir = wp_upload_dir();
// $wordpress_upload_dir['path'] is the full server path to wp-content/uploads/2020/11, for multisite works good as well
// $wordpress_upload_dir['url'] the absolute URL to the same folder, actually we do not need it, just to show the link to file
$i = 1; // number of tries when the file with the same name is already exists
$profilepicture = $_FILES['profilepicture'];
$new_file_path = $wordpress_upload_dir['path'] . '/' . $profilepicture['name'];
$new_file_mime = mime_content_type( $profilepicture['tmp_name'] );
if( empty( $profilepicture ) )
die( 'File is not selected.' );
if( $profilepicture['error'] )
die( $profilepicture['error'] );
if( $profilepicture['size'] > wp_max_upload_size() )
die( 'It is too large than expected.' );
if( !in_array( $new_file_mime, get_allowed_mime_types() ) )
die( 'WordPress doesn\'t allow this type of uploads.' );
while( file_exists( $new_file_path ) ) {
$i++;
$new_file_path = $wordpress_upload_dir['path'] . '/' . $i . '_' . $profilepicture['name'];
}
// looks like everything is OK
if( move_uploaded_file( $profilepicture['tmp_name'], $new_file_path ) ) {
$upload_id = wp_insert_attachment( array(
'guid' => $new_file_path,
'post_mime_type' => $new_file_mime,
'post_title' => preg_replace( '/\.[^.]+$/', '', $profilepicture['name'] ),
'post_content' => '',
'post_status' => 'inherit'
), $new_file_path );
// wp_generate_attachment_metadata() won't work if you do not include this file
require_once( ABSPATH . 'wp-admin/includes/image.php' );
// Generate and save the attachment metas into the database
wp_update_attachment_metadata( $upload_id, wp_generate_attachment_metadata( $upload_id, $new_file_path ) );
// Show the uploaded file in browser
wp_redirect( $wordpress_upload_dir['url'] . '/' . basename( $new_file_path ) );
}
我在网上查到的是这个,但是这个东西放哪里啊?是否还需要别的?
首先新建个HTML页面,里面写上加载quill前端编辑器的基本代码,直接参考quill官网的开发文档快速接入步骤说明即可。我这里就不贴HTML头部和底部了,自己写吧。
引入quill样式
<link href="https://cdn.quilljs.com/1.3.6/quill.snow.css" rel="stylesheet">
引入quill编辑器的js支持
<script src="https://cdn.quilljs.com/1.3.6/quill.js"></script>
quill编辑器加载容器
<div id="editor"></div>
quill编辑器初始化配置
<script>
var toolbarOptions = [
['bold', 'italic', 'underline', 'strike'], // toggled buttons
['blockquote', 'code-block'],
[{ 'header': 1 }, { 'header': 2 }], // custom button values
[{ 'list': 'ordered'}, { 'list': 'bullet' }],
[{ 'script': 'sub'}, { 'script': 'super' }], // superscript/subscript
[{ 'indent': '-1'}, { 'indent': '+1' }], // outdent/indent
[{ 'direction': 'rtl' }], // text direction
[{ 'size': ['small', false, 'large', 'huge'] }], // custom dropdown
[{ 'header': [1, 2, 3, 4, 5, 6, false] }],
[{ 'color': [] }, { 'background': [] }], // dropdown with defaults from theme
[{ 'font': [] }],
[{ 'align': [] }],
['image', 'video'],
['clean'] // remove formatting button
];
var quill = new Quill('#editor', {
modules: {
toolbar: toolbarOptions
},
theme: 'snow'
});
</script>
上面部分只是为了加载quill富文本编辑器而已,现在用浏览器访问下应该可以看到一个完整的富文本编辑器了,下面接着写上传图片的js代码。
重写编辑器的图片预览方法
<script>
var toolbar = quill.getModule('toolbar');
toolbar.addHandler('image', function () {
var fileInput = this.container.querySelector('input.ql-image[type=file]');
if (fileInput == null) {
fileInput = document.createElement('input');
fileInput.setAttribute('multiple', 'multiple');
fileInput.setAttribute('id', 'file');
fileInput.setAttribute('type', 'file');
fileInput.setAttribute('accept', 'image/*');
fileInput.setAttribute('name', 'files[]');
fileInput.classList.add('ql-image');
fileInput.addEventListener('change', function () {
if (fileInput.files != null && fileInput.files[0] != null) {
var formData = new FormData();
formData.append('files', fileInput.files[0]);
$.ajax({
url: '上传图片接口地址',
type: 'POST',
cache: false,
data: formData,
processData: false,
contentType: false
}).done(function (res) {
json1=eval("(" + res + ")");
console.log('>>>>>>'+json1.data.src);
var range = quill.getSelection(true);
quill.insertEmbed(range.index, 'image', json1.data.src);
quill.setSelection(range.index + 1);
}).fail(function (res) {
});
}
});
this.container.appendChild(fileInput);
}
fileInput.click();
});
</script>
好了,前端部分结束,下面是PHP实现的WordPress媒体上传接口,注意文件引用路径。
require dirname(__FILE__).'/../../../../wp-load.php';
//WordPress核心,根目录下,自己换
$file = $_FILES['files'];
if ( !empty( $file ) ) {
// 获取上传目录信息
$wp_upload_dir = wp_upload_dir();
// 将上传的图片文件移动到上传目录
$basename = $file['name'];
$filename = $wp_upload_dir['path'] . '/' . $basename;
$re = rename( $file['tmp_name'], $filename );
$attachment = array(
'guid' => $wp_upload_dir['url'] . '/' . $basename,
'post_mime_type' => $file['type'],
'post_title' => preg_replace( '/\.[^.]+$/', '', $basename ),
'post_content' => '',
'post_status' => 'inherit'
);
$attach_id = wp_insert_attachment( $attachment, $filename );
require_once( ABSPATH . 'wp-admin/includes/image.php' );
$attach_data = wp_generate_attachment_metadata( $attach_id, $filename );
wp_update_attachment_metadata( $attach_id, $attach_data );
$re = array('code'=>0,'msg'=>'上传成功','data'=>array('src'=>wp_get_attachment_url( $attach_id ),'title'=>''));
print_r(json_encode($re));
}
第二个版本是这样的