How to use action response in a plugin for rest api

530 Views Asked by At

This must be something very simple, but I cannot figure it out.

A theme has an ajax action function that updates user profile. Here's the code:

add_action( 'wp_ajax_nopriv_update_profile', 'update_profile' );
add_action( 'wp_ajax_update_profile', 'update_profile' );

if( !function_exists('update_profile') ):
    function update_profile(){
        //update profile discipline
        ......    
        echo json_encode( array( 'success' => true) );
        die();
    }
endif;

I'm working on a plugin, that extends a theme's functionality to rest api. Now I want to use the above action in my plugin, and do something after it has returned. But since it has die() at the end, I cannot continue my execution after action. Here's how I'm calling it in my plugin:

add_action( 'rest_api_init', function () {
    register_rest_route( 'mobile-api/v1', '/update-profile', array(
      'methods' => 'POST',
      'callback' => 'editProfile',
    ));
});
function editProfile() {
    do_action("wp_ajax_update_profile");

    $response = array(); //<---- this and next doesn't get executed
    $response["works"] = "Voila!";
    wp_send_json($response, 200);
}

I've tried ob_get_contents() but it won't go past the die method.

Editing the theme is not an option.

How can I avoid the die() from theme action and return my own response?

Or what is the best way to mimic an ajax request in PHP code.

Reason: There's a bug in original action. I want to rectify by undoing a thing, that was done in action.

1

There are 1 best solutions below

1
On

Reuse the function (or make it reusable if you can't). Do not mimic a regular WP-AJAX call from the REST API endpoint handler. You're just making things too complicated this way.