As we have seen previously how easy it is to create and interact with WordPress using its REST API. This blog will explore how to use this REST API to handle media on our site.

Using Default REST API Route

To upload an image using the default media route, we can use a POST request to the /wp-json/wp/v2/media endpoint.

curl --user 'user:pass' -X POST http://wp.local/wp-json/wp/v2/media \
    -H "Content-Type: image/png" \
    -H "Content-Disposition: attachment; filename=\"filename.png\"" \
    --data-binary @filename.png

Upon successful upload WordPress will process the image store it in the media library, and return the media data in a JSON response, which includes the media’s ID, URL, and other relevant metadata.

Custom Media Upload Handler with REST API

While WordPress provides a default endpoint for media uploads, its not uncommon to want to create a custom route for uploading media.

Defining the Custom Route and Handler

function image_upload_route() {
    register_rest_route('my/v1', '/upload-image', [
        'methods' => 'POST',
        'callback' => 'handle_image_upload',
        'permission_callback' => '__return_true',
    ]);
}

add_action('rest_api_init', 'image_upload_route');

function handle_image_upload(WP_REST_Request $request) {
    if (empty($_FILES['file'])) {
        return new WP_REST_Response('No file uploaded', 400);
    }

    $file = $_FILES['file'];

    // Validate file type
    $allowed_mime_types = ['image/jpeg', 'image/png', 'image/gif'];
    if (!in_array($file['type'], $allowed_mime_types)) {
        return new WP_REST_Response('Invalid file type', 400);
    }

    include_once ABSPATH.'wp-admin/includes/file.php';
    $upload = wp_handle_upload($file, array( 'test_form' => false ));

    if (isset($upload['error'])) {
        return new WP_REST_Response($upload['error'], 500);
    }

    // Create attachment in WordPress media library
    $attachment = [
        'post_mime_type' => $file['type'],
        'post_title'     => sanitize_text_field($file['name']),
        'post_content'   => '',
        'post_status'    => 'inherit',
    ];

    $attachment_id = wp_insert_attachment($attachment, $upload['file']);

    // Get the URL of the uploaded file
    $attachment_url = wp_get_attachment_url($attachment_id);

    // Return the response with attachment data
    return new WP_REST_Response([
        'id' => $attachment_id,
        'url' => $attachment_url,
        'mime_type' => $file['type'],
        'name' => $file['name'],
    ], 200);
}
  • Registering the Custom Route: We use register_rest_route to create a custom REST API route at /wp-json/my/v1/upload-image. This route is uses the handle_image_upload() function, which will handle the file upload logic.
  • Callback Function: Inside the callback function, we first check whether a file has been uploaded.
  • File Type Validation: We ensure that the uploaded file is one of the allowed image types (JPEG, PNG, or GIF). If the file type doesnt match we return an error message.
  • Handling the Upload: Using WordPress’s built-in wp_handle_upload function, we process the file. If the upload is successful, we move on to inserting it into the media library.
  • Inserting into the Media Library: We use wp_insert_attachment to insert the uploaded file into WordPress’s media library as an attachment. Then, we retrieve the URL of the uploaded file using wp_get_attachment_url.
  • Returning the Response: Finally, we send a JSON response back to the client with the attachment ID, URL, MIME type, and file name.

Uploading the Image with curl

To upload an image using this custom handler we can again use curl but this time, we need to target the custom route (/wp-json/my/v1/upload-image).

curl -X POST http://wp.local/wp-json/my/v1/upload-image -F "file=@filename.png"

Conclusion

In this post, we covered two ways of handling media uploads in WordPress using the REST API:

  1. Using WordPress’s default media route to upload files.
  2. Creating a custom media upload handler with our own logic.

By leveraging the WordPress REST API, we can easily integrate media functionality into our applications giving us more control over how media files are handled and processed.

Leave a Reply

Your email address will not be published. Required fields are marked *