WP_HTML_Tag_Processor::remove_attribute( string $name ): bool

In this article

Remove an attribute from the currently-matched tag.

Parameters

$namestringrequired
The attribute name to remove.

Return

bool Whether an attribute was removed.

Source

public function remove_attribute( $name ) {
	if ( $this->is_closing_tag ) {
		return false;
	}

	/*
	 * > There must never be two or more attributes on
	 * > the same start tag whose names are an ASCII
	 * > case-insensitive match for each other.
	 *     - HTML 5 spec
	 *
	 * @see https://html.spec.whatwg.org/multipage/syntax.html#attributes-2:ascii-case-insensitive
	 */
	$name = strtolower( $name );

	/*
	 * Any calls to update the `class` attribute directly should wipe out any
	 * enqueued class changes from `add_class` and `remove_class`.
	 */
	if ( 'class' === $name && count( $this->classname_updates ) !== 0 ) {
		$this->classname_updates = array();
	}

	/*
	 * If updating an attribute that didn't exist in the input
	 * document, then remove the enqueued update and move on.
	 *
	 * For example, this might occur when calling `remove_attribute()`
	 * after calling `set_attribute()` for the same attribute
	 * and when that attribute wasn't originally present.
	 */
	if ( ! isset( $this->attributes[ $name ] ) ) {
		if ( isset( $this->lexical_updates[ $name ] ) ) {
			unset( $this->lexical_updates[ $name ] );
		}
		return false;
	}

	/*
	 * Removes an existing tag attribute.
	 *
	 * Example – remove the attribute id from <div id="main"/>:
	 *    <div id="initial_id"/>
	 *         ^-------------^
	 *         start         end
	 *    replacement: ``
	 *
	 *    Result: <div />
	 */
	$this->lexical_updates[ $name ] = new WP_HTML_Text_Replacement(
		$this->attributes[ $name ]->start,
		$this->attributes[ $name ]->end,
		''
	);

	// Removes any duplicated attributes if they were also present.
	if ( null !== $this->duplicate_attributes && array_key_exists( $name, $this->duplicate_attributes ) ) {
		foreach ( $this->duplicate_attributes[ $name ] as $attribute_token ) {
			$this->lexical_updates[] = new WP_HTML_Text_Replacement(
				$attribute_token->start,
				$attribute_token->end,
				''
			);
		}
	}

	return true;
}

Changelog

VersionDescription
6.2.0Introduced.

User Contributed Notes

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