我正在使用一个具有图像上载/输入字段的表单,该表单允许经过身份验证的用户通过WP API创建和发布帖子。我可以使用创建后的功能,但是我只能添加特色图片部分。
我知道,要上传特色图片并将其分配给帖子,必须先创建帖子。
这是我正在考虑的代码,但是不确定哪种方法最适合成功和预期的结果。非常感谢您的帮助:
所需结果
到目前为止,我的代码在“发件人”提交时触发
// trigger when post form is submitted
$(document).on('submit', '#post_form', function(){
var jwt = getCookie('jwt');
// get form data
var post_form=$(this);
var form_data=JSON.stringify(post_form.serializeObject());
// submit form data to api to create post
$.ajaxSetup({
contentType : 'application/json',
data : form_data,
beforeSend: function (xhr) {
xhr.setRequestHeader('Authorization',"Bearer"+ jwt);
};
$.post("https://my-domain.here/wp-json/wp/v2/customendpoint").then(function(result) {
$(data).each(function(index, value) {
var postid = value.id;
}
// What goes here to grab postid?
// How do I assign variable to the file from the submitted form ??
// And can/how should I perform another POST to media endpoint with posid to assign feature image after post creation is complete?
$.ajaxSetup({
contentType : 'application/json',
data : form_data,
beforeSend: function (xhr) {
xhr.setRequestHeader('Authorization',"Bearer"+ jwt);
};
$.post("http://my-domain.here/wp-json/wp/v2/media").done(function(result) {
//something here to show success
});
});
return false;
});