【发布时间】:2017-11-02 16:15:36
【问题描述】:
感谢您查看我的问题。
问题
我需要能够上传与帖子相关联的特征图像(缩略图),正在处理的网站能够从网站的前端发布帖子。
已实现自定义代码
在提交后的表单中,我使用了文件类型的输入元素:
<form class="compose-post-form" method="POST" enctype="multipart/form-data">
...
<input type="file" name="featured" id="featured">
...
</form>
使用 jQuery AJAX 在表单提交时将数据发送到后端:
$.ajax({
type: 'post',
url: t_ajax_url.ajax_url,
data: $this.serialize() + "&tri_post_content="+article_content+"&article="+article,
beforeSend: function () {
is_sending = true;
},
success: function (data) {
//window.location.replace(get_homepage_url+'trisine');
var fd = new FormData();
var file = $('#featured').val();
fd.append("featured", file);
fd.append('action', 'thumbnail_up');
jQuery.ajax({
type: 'POST',
url: t_ajax_url.ajax_url,
data: fd,
contentType: false,
processData: false,
success: function(response){
console.log(response);
}
});
},
error: function(xhr, status, error) {
console.log(status);
}
});
这是保存缩略图的代码,现在我只是用帖子 ID 22 进行测试:
add_action( 'wp_ajax_thumbnail_up', 't_thumbnail_up' );
function t_thumbnail_up(){
$uploaddir = wp_upload_dir();
$file = $_FILE['featured'];
$uploadfile = $uploaddir['path'] . '/' . basename( $file['name'] );
move_uploaded_file( $file['tmp_name'] , $uploadfile );
$filename = basename( $uploadfile );
$wp_filetype = wp_check_filetype(basename($filename), null );
$attachment = array(
'post_mime_type' => $wp_filetype['type'],
'post_title' => preg_replace('/\.[^.]+$/', '', $filename),
'post_content' => '',
'post_status' => 'inherit',
'menu_order' => $_i + 1000
);
$attach_id = wp_insert_attachment( $attachment, $uploadfile );
update_post_meta(22, '_thumbnail_id',$attach_id);
set_post_thumbnail( 22, $thumbnail_id );
exit();
}
结果是上传了一些东西,但它似乎只是文件夹名称,即 11 月的月份数,该文件夹实际上并未在服务器上创建:
任何有关我如何使其工作的帮助将不胜感激。
【问题讨论】:
标签: php jquery ajax wordpress file-upload