Instead of using wp_ajax_
(i.e. admin-ajax.php
), how about adding a custom REST API field and then using its update_callback
, download the remote image and set it as the post featured image?
Working Example
add_action( 'rest_api_init', 'wpse_381217' );
function wpse_381217() {
register_rest_field( 'post', 'featured_image_url', array(
// If you don't want to expose the field in the REST API response, you
// may ignore the get_callback, i.e. don't set it.
'get_callback' => function ( $post_arr ) {
return get_the_post_thumbnail_url( $post_arr['id'], 'full' );
},
'update_callback' => function ( $url, $post_obj ) {
$file_array = array(
'name' => wp_basename( $url ),
'tmp_name' => download_url( $url ),
);
if ( is_wp_error( $file_array['tmp_name'] ) ) {
return false;
}
$id = media_handle_sideload( $file_array, 0 );
if ( is_wp_error( $id ) ) {
@unlink( $file_array['tmp_name'] );
return false;
}
return set_post_thumbnail( $post_obj->ID, $id );
},
'schema' => array(
'description' => 'Featured image URL.',
'type' => 'string',
),
) );
}
Then, in your OurPostData
variable, add the featured image URL with the name featured_image_url
. E.g.
const OurPostData = {
title: 'testing featured_image_url',
featured_image_url: 'https://example.com/image.png',
// ...
};