I am trying to create a post using the rest API. Which I am able to do with a fetch request as below. OurPostData
contains the title, content and URL of a featured image which is an external url
fetch('https://mywebste.online/wp-json/wp/v2/post', {
method: 'POST',
credentials: 'same-origin',
headers: new Headers({
'Content-Type': 'application/json;charset=UTF-8',
'X-WP-Nonce': qrAjax.nonce
}),
body: JSON.stringify(OurPostData),
}).then(response => {
console.log(response);
return response.json();
}).then(data => console.log(data));
});
This works except for the featured image. If I am able to do pass it to the callback function done using the below code may be I can achieve that?
add_action('wp_ajax_code_post_create', 'code_post_create_callback');
But I don't know how to pass it. The data
in my code has the post id. ( How can I access it in code_post_create_callback
?)
I can save the file using below
$file = 'https://externalwebsite.com/image.jpg';
$file_array = [ 'name' => wp_basename( $file ), 'tmp_name' => download_url( $file ) ];
// If error storing temporarily, return the error.
if ( is_wp_error( $file_array['tmp_name'] ) ) {
return $file_array['tmp_name'];
}
// Do the validation and storage stuff.
require_once ('wp-load.php');
require_once ('wp-admin/includes/admin.php');
$id = media_handle_sideload( $file_array, 0, $desc );
//var_dump($id);
// If error storing permanently, unlink.
if ( is_wp_error( $id ) ) {
@unlink( $file_array['tmp_name'] );
return $id;
}
How do I call code_post_create_callback
? How do I access the data
in this callback?