我目前正在使用Dropzone。js,我可以创建dropzone,但是当我传入plugins\\u url作为操作时,我希望获得文件并使用wordpress文档中常见的insert\\u附件功能将其添加到wordpress媒体。
Dropzone:
<form id="udev-dropzone" method = "post" action="<?php echo plugins_url(\'/unrealdevs-portfolio/library/components/PortfolioUploader.php\'); ?>" class="dropzone" enctype="multipart/form-data">
<input type="hidden" name="submitted" id="submitted" value="1" />
</form>
我在PortfolioUploader中的声明。php检查文件(我知道我需要添加nonce):
if ( $_FILES ) {
$files = $_FILES;
$user = $_POST[\'user_id\'];
foreach ($files[\'name\'] as $key => $value) {
if ($files[\'name\'][$key]) {
$file = array(
\'name\' => $files[\'name\'][$key],
\'type\' => $files[\'type\'][$key],
\'tmp_name\' => $files[\'tmp_name\'][$key],
\'error\' => $files[\'error\'][$key],
\'size\' => $files[\'size\'][$key]
);
$_FILES = array("upload_attachment" => $file);
update_udevdb($user, $file); //Dismiss this line.
foreach ($_FILES as $file => $array) {
$newupload = insert_attachment($file);
var_dump($file);
}
}
}
}
insert\\u附件功能:
function insert_attachment($file_handler) {
// check to make sure its a successful upload
if ($_FILES[$file_handler][\'error\'] !== UPLOAD_ERR_OK) __return_false();
require_once(ABSPATH . "wp-admin" . \'/includes/image.php\');
require_once(ABSPATH . "wp-admin" . \'/includes/file.php\');
require_once(ABSPATH . "wp-admin" . \'/includes/media.php\');
$attach_id = media_handle_upload( $file_handler, 0 );
}
有人能帮我吗?:)
EDIT: Here is the code that was used to correctly insert_attachment
function udev_before_uploader() {
if ( !empty($_FILES) ) {
$files = $_FILES;
foreach($files as $file) {
$newfile = array (
\'name\' => $file[\'name\'],
\'type\' => $file[\'type\'],
\'tmp_name\' => $file[\'tmp_name\'],
\'error\' => $file[\'error\'],
\'size\' => $file[\'size\']
);
$_FILES = array(\'upload\'=>$newfile);
foreach($_FILES as $file => $array) {
$newupload = insert_attachment($file);
}
}
}
}
最合适的回答,由SO网友:Milo 整理而成
我假设问题是您的表单以外部文件为目标,WordPress没有正确加载以访问API。
WordPress内置了一个处理程序,您可以通过admin_post
措施:
隐藏的示例窗体action
字段:
<form action="<?php echo admin_url( \'admin-post.php\' ); ?>" method="post">
<input type="hidden" name="action" value="add_foobar">
<input type="hidden" name="data" value="somedata">
<input type="submit" value="Submit">
</form>
示例操作,映射到
action
从表单传递:
add_action( \'admin_post_add_foobar\', \'prefix_admin_add_foobar\' );
//this next action version allows users not logged in to submit requests
add_action( \'admin_post_nopriv_add_foobar\', \'prefix_admin_add_foobar\' );
function prefix_admin_add_foobar() {
status_header(200);
// load your processing.php file
die();
}
WordPress将在此上下文中加载,使您能够访问表单处理代码中的API。