Create a new post using rest api and save featured image using an external image url

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?

Solutions

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',
    // ...
};

Similar questions

WooCommerce need to call an external API when new user created and new order placed
I want to trigger custom API calls in the WooCommerce website in the below scenarios I want to call 3 different api's when these actions are performed, any help would be highly appreciated.
How to Securely and remotely Create new user in wordpress using Rest API
I am trying to create users in wordpress Version 4.9.1, remotely using the wordpress API. This is my PHP code below: When i execute the code, create new user fails and this is error code I get: How can I securely and remotely Create new user in wordpress using wordpress Rest API?
Create a new user using WP REST API and declare meta object
I'm struggling here with a question. I'm sending a POST to http://localhost/wp-json/v2/wp/users/ with this JSON data: But when I go to see the result, the meta object is blank. I accomplished the goal using a plug-in, but this plug-in authenticates with cookie and I have another plug-in who uses JWT to authenticate, so I think is to much plug-ins t...
Wordpress REST API: How to get the "word-only" content in WP REST API JSON File?
I am using WP REST API to retrieve data from my website, for example, from this http: http://localhost:8888/wordpress/wp-json/wp/v2/posts/42 I can the the info of the post 42, but inside the content section, it shows like this the actual post is in the format: this is a test blog +[image]+this is a test blog+[image] all I want from the content sect...
WordPress acf-to-rest-api && Rest API
Activating ACF to REST API , breaks WP REST API If I activate WP REST API, I can retrieve data: ( currently both enabled on the site, so links will show error) http://ecommerce-ux.london/wp-json/wp/v2/posts?slug=hello-world http://ecommerce-ux.london/wp-json/wp/v2/posts/1 Current error responce is Above links don't work but if I do: http://ecommerc...

Also ask

We use cookies to deliver the best possible experience on our website. By continuing to use this site, accepting or closing this box, you consent to our use of cookies. To learn more, visit our privacy policy .