WP_Interactivity_API::data_wp_bind_processorprivateWP 6.5.0

Processes the data-wp-bind directive.

It updates or removes the bound attributes based on the evaluation of its associated reference.

Method of the class: WP_Interactivity_API{}

No Hooks.

Returns

null. Nothing (null).

Usage

// private - for code of main (parent) class only
$result = $this->data_wp_bind_processor( $p, $mode );
$p(WP_Interactivity_API_Directives_Processor) (required)
The directives processor instance.
$mode(string) (required)
Whether the processing is entering or exiting the tag.

Changelog

Since 6.5.0 Introduced.

WP_Interactivity_API::data_wp_bind_processor() code WP 7.0

private function data_wp_bind_processor( WP_Interactivity_API_Directives_Processor $p, string $mode ) {
	if ( 'enter' === $mode ) {
		$entries = $this->get_directive_entries( $p, 'bind' );
		foreach ( $entries as $entry ) {
			if ( empty( $entry['suffix'] ) || null !== $entry['unique_id'] ) {
					continue;
			}

			// Skip if the suffix is an event handler.
			if ( str_starts_with( $entry['suffix'], 'on' ) ) {
				_doing_it_wrong(
					__METHOD__,
					sprintf(
						/* translators: %s: The directive, e.g. data-wp-on--click. */
						__( 'Binding event handler attributes is not supported. Please use "%s" instead.' ),
						esc_attr( 'data-wp-on--' . substr( $entry['suffix'], 2 ) )
					),
					'6.9.2'
				);
				continue;
			}

			$result = $this->evaluate( $entry );

			if (
				null !== $result &&
				(
					false !== $result ||
					( strlen( $entry['suffix'] ) > 5 && '-' === $entry['suffix'][4] )
				)
			) {
				/*
				 * If the result of the evaluation is a boolean and the attribute is
				 * `aria-` or `data-, convert it to a string "true" or "false". It
				 * follows the exact same logic as Preact because it needs to
				 * replicate what Preact will later do in the client:
				 * https://github.com/preactjs/preact/blob/ea49f7a0f9d1ff2c98c0bdd66aa0cbc583055246/src/diff/props.js#L131C24-L136
				 */
				if (
					is_bool( $result ) &&
					( strlen( $entry['suffix'] ) > 5 && '-' === $entry['suffix'][4] )
				) {
					$result = $result ? 'true' : 'false';
				}
				$p->set_attribute( $entry['suffix'], $result );
			} else {
				$p->remove_attribute( $entry['suffix'] );
			}
		}
	}
}