I’m using the WP REST API to trigger a task from an AJAX request, my callback function attempts to trigger an action found within a plugin, however, that plugin doesn’t appear to have loaded.
The following code is within my functions.php
file:
add_action('rest_api_init', function() {
register_rest_route('foo/v1', '/capture-payments', array(
'methods' => 'POST',
'callback' => [$this, 'capturePayments'],
));
});
public static function capturePayments($request) {
// this action doesn't load, because the plugin hasn't loaded
if ( ! has_action('name_of_plugin_action') ) {
return new \WP_Error('payment_capture_not_available', 'Payment capture is not available', array('status' => 500));
}
...
}
My question is, is there a way to load the plugins for this API request, such that I can access their functionality as I would within a normal theme?
Edit 1:
It might be worth noting that this used within the admin, for purely backend purposes.
1 Answer
I have figured out the problem, after trying a load of things I wanted to double check plugins weren’t being loaded at all within the REST API.
I added some rudimentary debugging to the plugin in question and I saw that the plugin was indeed being loaded, my issue was that in these conditions the plugin itself wasn’t exposing functionality it would do under a normal request.
The do_action
I wanted to achieve therefore was failing, as it hadn’t been registered. I simply invoked the class that registered the action and now my code works as desired.