For the complete documentation index, see llms.txt. This page is also available as Markdown.

Custom Ajax & Rest API

About the feature

Advanced Views has the PHPController feature for Layouts and Post Selections, allowing extensive customization of components. In addition to passing extra arguments as mentioned in the linked guides, you can also add AJAX and REST API listeners to your components.

This feature builds on top of the built-in WordPress Ajax and REST API, enabling you to create components that can send data and update themselves in the background without refreshing the page.

To use this feature, override the get_ajax_response() or get_rest_api_response() method inside the Custom_Data instance. The return value should be an array, which will be passed as JSON to the client.

On the client side, you need to send requests to the admin-ajax.php file for AJAX scenarios, or to /wp-json for REST API scenarios.

Within the callback, you can use any WordPress functions. Furthermore, you can employ PHP-DI to get direct access to your theme classes.

Tip: Not sure about the difference between AJAX and REST API? If you don’t have specific limitations, we recommend using the REST API. It is much faster compared to the traditional admin-ajax.php as it skips loading unnecessary WordPress parts (while still making all necessary WordPress functions available, as it is called on the init action).

Example of Rest API usage

JavaScript code

For your Layout or PostSelection.

Use the script.js file of the target item if FS Mode is enabled

async function makeRequest(postId, value) {
// 1. todo use '/wp-json/advanced_views/v1/layout/' for Layout, 
// and put your Layout ID at the end

// 2. todo use '/wp-json/advanced_views/v1/card/' for Cards, 
// and put your Post Selection ID at the end

    await fetch('/wp-json/advanced_views/v1/{layout|post-selection}/{6630e2da1953e}', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({
        // todo your arguments here
           'postId': postId,
            'value': 'value,
        }),
    }).then(response => response.json())
        .then((response) => {
            // todo process response, the variable already contains the parsed object 
            console.log('Request complete', response);
        })
        .catch(error => () => {
            console.error('Request error:', error)
        });
}

PHP Controller code

For your Layout or PostSelection.

Use the controller.php file of the target item if FS Mode is enabled.

Request Authentication

The REST API is available to both authorized users and guests. However, for security reasons, by default REST API ignores the WordPress auth cookie, and treats the request as if it comes from an unauthorized user. E.g. 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 it described in the official WordPress Developer Documentation. In this cases WordPress will respect the user's auth cookie.

Below, we provide the auth example adopted for usage inside the Advanced Views Framework:

1. Create and pass nonce to the template (in controller.php)

2. Define nonce as a JS window variable (in Twig or Blade template)

3. Use nonce in the request headers (script.js)

Example of Ajax usage

script.js

Layout's controller.php

Post Selection's controller.php

Request Authentication

Ajax is available to both authorized users and guests. Unlike the REST API, Ajax does not ignore the WordPress authentication cookie, so it sets up the current user out-of-the-box without requiring any extra actions.

Last updated