在处理表单时,我很难弄清楚如何将wp\\u handle\\u upload()与ajax结合使用。我在这里所做的是使用一个表单,允许用户从前端编辑帖子,这样他们可以做一些事情,比如更改帖子的图像,这样我们就可以从这里开始了。
为了保持简单,我将省略这个函数的部分,包括错误检查。
// Process the edit form
add_action(\'wp_ajax_process_edit_form\', \'process_edit_form\');
function process_edit_form() {
require_once(ABSPATH . "wp-admin" . \'/includes/image.php\');
require_once(ABSPATH . "wp-admin" . \'/includes/file.php\');
require_once(ABSPATH . "wp-admin" . \'/includes/media.php\');
$image_file = $_POST[\'imageFile\'];
$image_file_name = $_POST[\'imageFileName\'];
$post_to_edit = get_post($_POST[\'postId\']);
// Set Image File
if ($image_file["size"] > 0) {
$cover_art_id = media_handle_sideload( $album_cover, $pid );
wp_set_object_terms( $cover_art_id, \'cover_art\', \'category\');
update_post_meta($pid,\'music_art\',$cover_art_id);
}
}
和基本html表单<form enctype="multipart/form-data">
<input type="file" name="image_file" id="image_file" />
<input type="submit" value="Save Changes" tabindex="6" id="submit" name="submit" data-id="<?php echo $post->ID; ?>" />
</form>
现在是一些jquery。请注意,这个jquery的脚本已经本地化,表单中的所有其他内容都可以使用我的方法正常工作。唯一不起作用的是提交时上传文件。$(document).on("click","#submit", function(e) {
e.preventDefault();
$this = $(this);
postId = $this.data("id");
imageFile = $this.closest("form").find("#image_file").val();
if (imageFile != "") {
imageFileName = $this.closest("form").find("#image_file").val().split(\'\\\\\').pop();
} else {
imageFileName = "none";
};
data = {
action: \'process_edit_form\',
postId : postId,
imageFile : imageFile,
imageFileName : imageFileName
};
$.post(ajaxurl, data, function (response) {
});
});
我可能会在传输时出错,但这基本上就是我正在做的。那么,为什么这不起作用呢?我看到了this answer 也就是说,我需要使用某种类型的ajax上传插件,但如果我不了解如何使用它们将上传保存为附件,我希望不用它。纠正我!