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

Selection Interactivity API

In Advanced Views, Post Selections support WordPress Interactivity API out of the box. It means you can use any directives in any template.

Since WordPress 6.5, the Interactivity API is a built-in part of WordPress. It's a standard system of directives, based on declarative code, for adding front-end interactivity to blocks. Similar to React or Vue, it offers a declarative approach and provides server-side rendering out-of-the-box. If you're new to the WordPress Interactivity API, we recommend reading a detailed explanation on our blog.

1. Post Selection Interactivity API example

Template field (vanilla PHP)

<?php
wp_interactivity_state('my-unique-name', [
    'isHidden' => false,
]);
?>

<div
    data-wp-interactive="my-unique-name"
    <?= wp_interactivity_data_wp_context([
        'layoutID' => $_selection['layout_id'],
    ]) ?>
>
    <div data-wp-bind--hidden="state.isHidden">
        My Layout ID is <span data-wp-text="context.layoutID"></span>
    </div>

    <button data-wp-on--click="actions.toggle">
        Toggle
    </button>
</div>

JavaScript field

2. Interactivity API cheatsheet

2.1) Block name

To use the WP Interactivity API, you should add data-wp-interactive='x' to the top tag of your element. The name can be any, but we recommend using the Layout or Post Selection name or ID.

2.2) Context

Using data-wp-context, you can declare any variables of the template as context, which will be used in directives and available in the JS code. Don't forget to use the Twig json_encode filter to turn the object into a string, as shown in the example.

2.3) State

Using the wp_interactivity_state function, you can declare any variables of the template as state, which will be used in directives and available in JS code. This function must be called before the data-wp-interactive attribute, so you should place it above the top tag of your template. Check the WP documentation to understand the difference between state and context.

2.3) @wordpress/interactivity package

WP Interactivity employs modules, which are already supported in all modern browsers. The @wordpress/interactivity package is an alias for the built-in WP interactivity script, which will be enqueued as a module automatically, so you don't need to worry about manual enqueueing in your theme.

2.4) Server-Side Rendering

The directives will initially be processed on the server side. For example, if you change the isHidden state to true, the div with the hidden bind will have the hidden attribute inside the HTML, so the client won't wait until the JS executes to hide that div.

WP also takes care of hydration/rehydration, keeping everything in sync when you change state or context in the JS code during client-side execution as well.

Last updated