1

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?

1 Answer 1

0

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',
    // ...
};
4
  • That's an awesome idea. Thank you
    – user145078
    Jan 11, 2021 at 3:07
  • Is there any callback function for fetch() like the jquery ajax , data{ action : callbackfunction ). Just learning new things I do really like the fetch for its similicity :)?
    – user145078
    Jan 11, 2021 at 3:10
  • 1
    The .then(data => console.log(data)) in your JS (in the question) is where you could run the callback, e.g. make another REST API request, e.g. uploading a file via the default /wp/v2/media endpoint - .then( data => { fetch( ... ); ... } ). Or am I not understanding what you mean?
    – Sally CJ
    Jan 11, 2021 at 7:23
  • 1
    oh yes. I can call another request in there. Thanks again
    – user145078
    Jan 11, 2021 at 7:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.