WP_HTML_Processor::set_attributepublicWP 6.6.0

Updates or creates a new attribute on the currently matched tag with the passed value.

This function handles all necessary HTML encoding. Provide normal, unescaped string values. The HTML API will encode the strings appropriately so that the browser will interpret them as the intended value.

Example:

// Renders “Eggs & Milk” in a browser, encoded as `<abbr title="Eggs & Milk">`.
$processor->set_attribute( 'title', 'Eggs & Milk' );
// Renders “Eggs & Milk” in a browser, encoded as `<abbr title="Eggs &amp; Milk">`.
$processor->set_attribute( 'title', 'Eggs & Milk' );
// Renders `true` as `<abbr title>`.
$processor->set_attribute( 'title', true );
// Renders without the attribute for `false` as `<abbr>`.
$processor->set_attribute( 'title', false );

Special handling is provided for boolean attribute values:

  • When true is passed as the value, then only the attribute name is added to the tag.
  • When false is passed, the attribute gets removed if it existed before.

Method of the class: WP_HTML_Processor{}

No Hooks.

Returns

true|false. Whether an attribute value was set.

Usage

$WP_HTML_Processor = new WP_HTML_Processor();
$WP_HTML_Processor->set_attribute( $name, $value ): bool;
$name(string) (required)
The attribute name to target.
$value(string|true|false) (required)
The new attribute value.

Changelog

Since 6.6.0 Introduced.
Since 6.6.0 Subclassed for the HTML Processor.
Since 6.9.0 Escapes all character references instead of trying to avoid double-escaping.

WP_HTML_Processor::set_attribute() code WP 7.0

public function set_attribute( $name, $value ): bool {
	return $this->is_virtual() ? false : parent::set_attribute( $name, $value );
}