Selection Rest Api actions
In Advanced Views, every Post Selection is a smart entity, natively supporting the WordPress Rest Api.
It enables you to create components that can send data and/or update themselves in the background without refreshing the page.
Server side:
To use this feature, we override the get_rest_api_response() method inside the Selection Controller instance. The return value should be an array, which will be passed as JSON to the client.
Within the callback, you can use any WordPress functions. Furthermore, you can employ PHP-DI to get direct access to your theme classes.
Client side:
On the client side, as usual, we send requests to the /wp-json endpoint.
1. Rest Api vs. Ajax
Not sure about the difference between WordPress Ajax and REST API?
In most cases, we recommend using the REST API. It is much faster compared to the traditional admin-ajax.php requests, as it skips loading unnecessary WordPress parts - while still making all necessary WordPress functions available - as it is called during the WordPress init action.
If you need to work with authorized users, Ajax may be the simpler option, as it respects the auth cookie within requests; therefore, it doesn't require Request Authentication parts.
2. Selection Rest Api example
JavaScript code
Incorporate the following function into your Post Selection's JavaScript code:
Selection Controller code
Incorporate the following function into your Selection Controller:
3. Request Authentication
The REST API is available to both authorized users and guests; however:
It means wp_get_current_user()->exists() method inside the request will return false.
If you need to keep the user authorized inside the request, you must create a wp_rest nonce and pass it in the X-WP-Nonce header, as is described in the official WordPress Developer Documentation. In this case, WordPress will respect the user's auth cookie.
Below, we provide the auth example adopted for use inside the Advanced Views:
3.1) Selection Controller: create and pass nonce to the template
3.2) Selection template: define nonce as a JavaScript variable
3.3) Selection JavaScript: use nonce in the request headers
Last updated