I'm brand new to Wordpress development; Trying to return an image from a custom endpoint, but it seems to want to serialize everything to JSON.

I did manage to get it to work using echo. Is that a hack?

I also tried using WP_HTTP_Response, but that didn't seem to work.

My code:

require 'vendor/autoload.php';

use Intervention\Image\ImageManagerStatic as Image;

function prefix_generate_cover_photo($data) {
    $image = Image::make(plugin_dir_path(__FILE__) . 'image.png')->response();
    $response = new WP_REST_Response($image, 200, array(
        'Content-Type' => 'image/png'
    return $response;

add_action( 'rest_api_init', function () {
    register_rest_route( 'prefix/v1', '/photo', array(
        'methods' => 'GET',
        'callback' => 'prefix_generate_cover_photo',

This works but I'm not sure if it's good practice:

function prefix_generate_cover_photo($data) {
    echo Image::make(plugin_dir_path(__FILE__) . 'image.png')->response();

Any ideas?

1 Answer 1


echo in the rest-api and not valid! You should using return to make output to Rest API.

For example:

function prefix_generate_cover_photo( WP_REST_Request $request ) {
    // Get method params
    $params = $request->get_params();

    // Data
    $data = array(
        'url'   => 'The image url',
        'title' => 'The image title',

    // Create the response object
    $response = new WP_REST_Response( array( 'image' => $data ) );

    // Add a custom header (Optional)
    //$response->header( 'Cache-Control', 'no-cache' );

    return $response;
  • 1
    That's what I was thinking, but returning a url to the image won't work in my case, I need to return the image itself as the response. Is there a way to do that with the REST API? Or is there another recommended way of doing this in wordpress?
    – nfw
    Oct 3, 2017 at 16:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.