我想在前端表单上上传AJAX图像,但我不知道哪里出了问题。
用于图像上载的HTML表单
<form id="thumbnail_upload" method="post" action="#" enctype="multipart/form-data" >
<input type="file" name="thumbnail" id="thumbnail">
<input type=\'hidden\' value=\'<?php wp_create_nonce( \'upload_thumb\' ); ?>\' name=\'_nonce\' />
<input type="hidden" name="action" id="action" value="my_upload_action">
<form>
<div id="output1"></div>
<script>
jQuery(document).ready( function($) {
//http://wordpress.stackexchange.com/questions/72406/set-featured-image-front-frontend-form
var ajaxurl = \'<?php echo admin_url(\'admin-ajax.php\'); ?>\';
var options = {
target: \'#output1\', // target element(s) to be updated with server response
beforeSubmit: showRequest, // pre-submit callback
success: showResponse, // post-submit callback
url: ajaxurl // since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php
};
$(\'#thumbnail\').change(function(){
// bind form using \'ajaxForm\'
$(\'#thumbnail_upload\').ajaxSubmit(options);
});
function showRequest(formData, jqForm, options) {
//do extra stuff before submit like disable the submit button
$(\'#output1\').html(\'Uploading...\');
}
function showResponse(responseText, statusText, xhr, $form) {
//do extra stuff after submit
}
});
</script>
下面是处理图像上传的PHP
media_handle_upload
// Enqueue jquery form
function load_jform() {
wp_enqueue_script( \'jquery-form\' );
}
add_action( \'wp_enqueue_scripts\', \'load_jform\' );
//hook the Ajax call
//for logged-in users
add_action(\'wp_ajax_my_upload_action\', \'my_ajax_upload\');
function my_ajax_upload(){
//simple Security check
check_ajax_referer(\'upload_thumb\');
//get POST data
$post_id = 0;
//require the needed files
require_once(ABSPATH . "wp-admin" . \'/includes/image.php\');
require_once(ABSPATH . "wp-admin" . \'/includes/file.php\');
require_once(ABSPATH . "wp-admin" . \'/includes/media.php\');
//then loop over the files that were sent and store them using media_handle_upload();
var_dump($_FILES);
if ($_FILES) {
foreach ($_FILES as $file => $array) {
if ($_FILES[$file][\'error\'] !== UPLOAD_ERR_OK) {
echo "upload error : " . $_FILES[$file][\'error\'];
die();
}
$attach_id = media_handle_upload( $file, $post_id );
}
}
//and if you want to set that image as Post then use:
update_post_meta($post_id,\'_thumbnail_id\',$attach_id);
echo "uploaded the new Thumbnail";
die();
}
我其实不需要
foreach
循环上载多个图像,因为它将只显示一个特征图像,但无法确定如何正确更改它。
有了这些代码0
在…上#output1
我不知道在哪里或者如何调试这个。