WP_HTML_Tag_Processor::get_attribute
Returns the value of a requested attribute from a matched tag opener if that attribute exists.
Example:
$p = new WP_HTML_Tag_Processor( '<div enabled class="test" data-test-id="14">Test</div>' ); $p->next_tag( array( 'class_name' => 'test' ) ) === true; $p->get_attribute( 'data-test-id' ) === '14'; $p->get_attribute( 'enabled' ) === true; $p->get_attribute( 'aria-label' ) === null;
$p->next_tag() === false; $p->get_attribute( 'class' ) === null;
Method of the class: WP_HTML_Tag_Processor{}
No Hooks.
Returns
String|true|null. Value of attribute or null if not available. Boolean attributes return true.
Usage
$WP_HTML_Tag_Processor = new WP_HTML_Tag_Processor(); $WP_HTML_Tag_Processor->get_attribute( $name );
- $name(string) (required)
- Name of attribute whose value is requested.
Changelog
| Since 6.2.0 | Introduced. |
WP_HTML_Tag_Processor::get_attribute() WP HTML Tag Processor::get attribute code WP 6.9
public function get_attribute( $name ) {
if ( self::STATE_MATCHED_TAG !== $this->parser_state ) {
return null;
}
$comparable = strtolower( $name );
/*
* For every attribute other than `class` it's possible to perform a quick check if
* there's an enqueued lexical update whose value takes priority over what's found in
* the input document.
*
* The `class` attribute is special though because of the exposed helpers `add_class`
* and `remove_class`. These form a builder for the `class` attribute, so an additional
* check for enqueued class changes is required in addition to the check for any enqueued
* attribute values. If any exist, those enqueued class changes must first be flushed out
* into an attribute value update.
*/
if ( 'class' === $name ) {
$this->class_name_updates_to_attributes_updates();
}
// Return any enqueued attribute value updates if they exist.
$enqueued_value = $this->get_enqueued_attribute_value( $comparable );
if ( false !== $enqueued_value ) {
return $enqueued_value;
}
if ( ! isset( $this->attributes[ $comparable ] ) ) {
return null;
}
$attribute = $this->attributes[ $comparable ];
/*
* This flag distinguishes an attribute with no value
* from an attribute with an empty string value. For
* unquoted attributes this could look very similar.
* It refers to whether an `=` follows the name.
*
* e.g. <div boolean-attribute empty-attribute=></div>
* ¹ ²
* 1. Attribute `boolean-attribute` is `true`.
* 2. Attribute `empty-attribute` is `""`.
*/
if ( true === $attribute->is_true ) {
return true;
}
$raw_value = substr( $this->html, $attribute->value_starts_at, $attribute->value_length );
return WP_HTML_Decoder::decode_attribute( $raw_value );
}