WP_Interactivity_API::print_client_interactivity_data()

In this article

Prints the serialized client-side interactivity data.

Description

Encodes the config and initial state into JSON and prints them inside a script tag of type "application/json". Once in the browser, the state will be parsed and used to hydrate the client-side interactivity stores and the configuration will be available using a getConfig utility.

Source

public function print_client_interactivity_data() {
	if ( empty( $this->state_data ) && empty( $this->config_data ) ) {
		return;
	}

	$interactivity_data = array();

	$config = array();
	foreach ( $this->config_data as $key => $value ) {
		if ( ! empty( $value ) ) {
			$config[ $key ] = $value;
		}
	}
	if ( ! empty( $config ) ) {
		$interactivity_data['config'] = $config;
	}

	$state = array();
	foreach ( $this->state_data as $key => $value ) {
		if ( ! empty( $value ) ) {
			$state[ $key ] = $value;
		}
	}
	if ( ! empty( $state ) ) {
		$interactivity_data['state'] = $state;
	}

	if ( ! empty( $interactivity_data ) ) {
		wp_print_inline_script_tag(
			wp_json_encode(
				$interactivity_data,
				JSON_HEX_TAG | JSON_HEX_AMP
			),
			array(
				'type' => 'application/json',
				'id'   => 'wp-interactivity-data',
			)
		);
	}
}

Changelog

VersionDescription
6.5.0Introduced.

User Contributed Notes

You must log in before being able to contribute a note or feedback.