Advanced Views Docs
Live PlaygroundDownload PluginGet PRO
  • πŸ’‘Help Centre
  • ⚑Getting Started
    • Introduction
      • Key Aspects
      • Creating Your First View
      • Creating Your First Card
      • Plugin Terms
      • Plugin Interface
        • Field Options
    • Installation
      • Advanced Views Lite
      • Advanced Views Pro
      • Comparison Table
      • Upgrading from Lite to Pro
    • Supported data vendors
    • Starter theme
  • 🌟Display Content
    • WordPress
      • Post
      • Taxonomy terms
      • User
      • Comments
      • Menus
    • WooCommerce Product
    • Meta fields
      • Basic fields
        • Number
      • Content fields
        • Image
        • File
        • WYSIWYG
        • oEmbed
        • Gallery
      • Choice fields
        • Select/checkbox/radio
        • True / False
      • Relationship fields
        • Link
        • Post_object
        • Page Link
        • Relationship
        • Taxonomy
        • User
      • Advanced fields
        • Google Map
        • Google Map Multiple Markers
        • ACF OpenStreetMap Field
        • Date/time picker
      • Layout fields
        • Group (Pro)
        • Repeater (Pro)
        • Flexible (Pro)
    • Object fields
    • Custom Data (Pro)
    • Custom Gutenberg Blocks (Pro)
    • Mount Points (Pro)
    • Front-end assets management (Pro)
  • πŸ¦Έβ€β™‚οΈQuery Content
    • Basic Filters
    • Meta Filters (Pro)
      • Current Post
      • Comparison
      • Dynamic Injection
    • Taxonomy Filters (Pro)
    • Pagination (Pro)
    • Custom Data (Pro)
  • πŸ†Shortcode Attributes
    • Common Arguments
    • View Shortcode
    • Card Shortcode
  • πŸ§™β€β™‚οΈTemplates
    • Customizing the Template
    • Template engines
      • Twig
      • Blade
    • CSS & JS
      • BEM Methodology
      • WordPress Interactivity API
    • File system storage
    • Pre-built components
    • Reusable components library (Pro)
    • Live reload
    • Multilingual
    • Custom Ajax & Rest API (Pro)
  • β˜•Guides
    • Display Custom Post Type (CPT) on another post
    • Display Employees (CPT) of a Company (CPT)
    • Display Nested Repeater Fields
    • Map Marker from ACF Image
    • Display all CPT items on a single map
  • πŸ› οΈTools
    • Export/Import
    • Demo Import
    • Settings
    • Preview
  • 🏹Troubleshooting
    • Compatibility
    • Report a bug
    • Payment Issues
    • Lite Support (Forum)
    • Pro Support
  • βš™οΈCustomization
    • Filters and Hooks
      • View
      • Card
    • Suggest a feature
    • Performance
Powered by GitBook
On this page
  • About the feature
  • Example of Rest API usage
  • script.js
  • view.php
  • card.php
  • Request Authentication
  • Example of Ajax usage
  • script.js
  • view.php
  • card.php
  • Request Authentication

Was this helpful?

  1. Templates

Custom Ajax & Rest API (Pro)

PreviousMultilingualNextDisplay Custom Post Type (CPT) on another post

Last updated 9 months ago

Was this helpful?

About the feature

The Pro edition has the Custom_Data feature for and , allowing for 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 and , 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 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

script.js

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

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

    await fetch('/wp-json/advanced_views/v1/{view|card}/{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)
        });
}

view.php

<?php

declare( strict_types=1 );

use Org\Wplake\Advanced_Views\Pro\Bridge\Views\Custom_View_Data;

return new class extends Custom_View_Data {

	/**
	 * @return array<string,mixed>
	 */
	public function get_rest_api_response( WP_REST_Request $request ): array {
		$request_arguments = $request->get_json_params();
		// todo process the request, based on the query arguments available inside the $input array

		// todo you can use the container if you need to access your theme classes
		// $this->get_container();

		return [
			'my_message'  => 'everything is fine',
			'my_variable' => 'my value',
		];
	}
};

card.php

<?php

declare( strict_types=1 );

use Org\Wplake\Advanced_Views\Pro\Bridge\Cards\Custom_Card_Data;

return new class extends Custom_Card_Data {

	/**
	 * @return array<string,mixed>
	 */
	public function get_rest_api_response( WP_REST_Request $request ): array {
		$request_arguments = $request->get_json_params();
		// todo process the request, based on the query arguments available inside the $input array

		// todo you can use the container if you need to access your theme classes
		// $this->get_container();

		return [
			'my_message'  => 'everything is fine',
			'my_variable' => 'my value',
		];
	}
};

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.

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

1. Create and pass nonce to the template (in view.php or card.php)

// ...
/**
 * @return array<string,mixed>
 */
public function get_variables(): array {
  return [
    "my_block_nonce" => wp_create_nonce( 'wp_rest' ),
  ];
}
// ...

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

<!-- ... -->
<script>
window.my_block_nonce = "{{ my_block_nonce }}";
</script>
<!-- ... -->

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

// ...
await fetch('/wp-json/advanced_views/v1/{view|card}/{6630e2da1953e}', {
 method: 'POST',
 headers: {
  'Content-Type': 'application/json',
  'X-WP-Nonce': window.my_block_nonce,
},
// ...

Example of Ajax usage

script.js

async function makeAjax() {
    let response = await fetch('/wp-admin/admin-ajax.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: new URLSearchParams({
            'action': 'advanced_views',
            // todo put your View ID or comment if it's a View 
            '_viewId': '6630e2da1953e', // you can learn ID from the shortcode
            // todo put your Card ID or comment if it's a Card 
            '_cardId': '6630e2da1953e', // you can learn ID from the shortcode
            // todo your args here
            'myArg': 'myvalue',
        }).toString(),
    });

    let responseText = await response.text();
    let json = {};

    try {
        json = JSON.parse(responseText);
    } catch (e) {
        console.log("Error parsing JSON", responseText);
        return;
    }

    console.log('ajax complete', json);
}

view.php

<?php

declare( strict_types=1 );

use Org\Wplake\Advanced_Views\Pro\Bridge\Views\Custom_View_Data;

return new class extends Custom_View_Data {
	public function get_ajax_response(): array {
		$myArg = sanitize_text_field( $_POST['myArg'] ?? '' );

		// todo your logic here
		// additionally, you can use $this->get_container()
		// to get PHP-DI instance and access to any of your theme classes

		return [
			'my_response' => 'Thank you for the feedback!',
		];
	}
};

card.php

<?php

declare( strict_types=1 );

use Org\Wplake\Advanced_Views\Pro\Bridge\Cards\Custom_Card_Data;

return new class extends Custom_Card_Data {
	public function get_ajax_response(): array {
		$myArg = sanitize_text_field( $_POST['myArg'] ?? '' );

		// todo your logic here
		// additionally, you can use $this->get_container()
		// to get PHP-DI instance and access to any of your theme classes

		return [
			'my_response' => 'Thank you for the feedback!',
		];
	}
};

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.

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 in the official WordPress Developer Documentation. In this cases WordPress will respect the user's auth cookie.

πŸ§™β€β™‚οΈ
it described
Views
Cards
WordPress Ajax
REST API
PHP-DI