通过AJAX上传缩略图帖子类型前端

时间:2017-01-14 02:13:14

标签: php ajax wordpress image upload

我有一个专业的注册表格,输入名称和图像(照片)。这个文件在Ajax中使用,我可以做到,但它必须在Ajax中完成,而且我无法发送图像,即使使用formData也是如此。这是我的代码目前的方式。

页面register.php

<form id="form-professionals">
  <input type="text" id="name" name="name" required placeholder="Insert the Name" value=""/>
  <input type="file" name="image" id="image">
  <button id="button-register-professionals">Register</button>
  <div class="notification-profesionals"></div>
</form>

scripts.js中

$(document).ready(function () {
$('#button-register-professionals').click(function () {
var name = $('#name').val();
var image = $('#image').val();
if (name == '') {
    alert('Required Field');
} else {
    $.ajax({
        type: 'POST',
        url: ajaxurl,
        data: {
            action: 'register_professionals',
            name: name,
            image: image
        },
        success: function (response) {
            $('.notification-profesionals').html(response);

        },

        error: function (response) {
            console.log('error: ' + response);
        }
    });
}
return false;
});
});

的functions.php

add_action('wp_ajax_nopriv_register_professionals', 'register_professionals');
add_action('wp_ajax_register_professionals', 'register_professionals');

function register_professionals(){
$post_type = 'professionals';
$title = $_POST['name'];
$image = $_FILES['image'];


$new_post = array(
'post_title' => $title,
'post_status' => 'pending',
'post_type' => $post_type,

);

wp_insert_post($new_post);

if (!function_exists('wp_generate_attachment_metadata')) {
require_once(ABSPATH . "wp-admin" . '/includes/image.php');
require_once(ABSPATH . "wp-admin" . '/includes/file.php');
require_once(ABSPATH . "wp-admin" . '/includes/media.php');
}
if ($image) {

foreach ($image as $file => $array) {
    if ($image[$file]['error'] !== UPLOAD_ERR_OK) {
        return "upload error : " . $image[$file]['error'];
    }
    $attach_id = media_handle_upload($file, $id);
}
} else {
echo 'error - image';
}
if ($attach_id > 0) {
update_post_meta($id, '_thumbnail_id', $attach_id);
echo 'success - add image';

} else {
echo 'error - add image';
}

if ($id) {
echo 'Success';
} else {
echo 'Error';
}
die();
}

0 个答案:

没有答案