Search code examples
phpwordpresswordpress-rest-api

How to separate code to another functions in wordpress custom rest route callback?


I have a custom rest route in my wordpress:

add_action( 'rest_api_init', function () {
  register_rest_route( 'site', '/test-route', array(
    'methods' => 'POST',
    'callback' => 'handle_webhook',
  ) );
} );

Everything worked perfectly fine but I'm making a refactor now and I'd like to change the previous code:

function handle_webhook( $request ) {
    
    //
    // processing
    //

    return new WP_REST_Response('Done, bro!', 200);
    die();

}

into:

function another_function_1( $request ) {
    //
    // processing
    //

    return new WP_REST_Response('Done from 1, bro!', 200);
    die();
}

function another_function_2( $request ) {
    //
    // processing
    //

    return new WP_REST_Response('Done from 2, bro!', 200);
    die();
}

function handle_webhook( $request ) {
    
    if ($something) {
        another_function_1( $request );
    } else {
        another_function_2( $request );
    }


    return new WP_REST_Response('Done, bro!', 200);
    die();

}

So in general I'd like to separate the code to another functions. The problem is that I'm always receiving the response from the main function ('Done, bro!', 200).

When I put the return to if statement it works:

if ($something) {
    return new WP_REST_Response('works here!', 200);
} else {
    return new WP_REST_Response('works also here when $something is !true', 200);
}

But from another functions I'm enable to return a response.

How can I achieve that?


Solution

  • You need to return the function () :

    function another_function_1( $request ) {
        //
        // processing
        //
    
        return new WP_REST_Response('Done from 1, bro!', 200);
        /** die(); */
    }
    
    function another_function_2( $request ) {
        //
        // processing
        //
    
        return new WP_REST_Response('Done from 2, bro!', 200);
        /** die(); */
    }
    
    function handle_webhook( $request ) {
        
        if ($something) {
            return another_function_1( $request ); /** Added return */
        } else {
            return another_function_2( $request ); /** Added return */
        }
    
        /** With the if {} else {} above, this code will never be reached.    
        /** return new WP_REST_Response('Done, bro!', 200); */
        /** die(); */
    
    }
    

    Otherwise, it just keeps moving on beyond the function call.

    Also, there is no need to die(); after a return, the code is mute, since the process never comes to that point in the code.