Created
June 18, 2023 07:46
-
-
Save gh640/9d9265056eee02bdfaca87ce7373d4f4 to your computer and use it in GitHub Desktop.
Sample: Using `WP_HTML_Tag_Processor` that is introduced WordPress 6.2.0
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* `WP_HTML_Tag_Processor` Modifies attributes in an HTML document for tags matching a query. | |
*/ | |
$html = '<span><img src="hello.webp" alt="hello"></span>'; | |
// Create an instance | |
$tags = new WP_HTML_Tag_Processor( $html ); | |
// Seek next tags | |
$tags->get_tag(); // => NULL | |
$tags->next_tag(); | |
$tags->get_tag(); // => 'SPAN' | |
// Handle attributes | |
$tags->set_attribute( 'class', 'myclass' ); | |
$tags->get_attribute( 'class' ); // => 'myclass' | |
$tags->remove_attribute( 'class' ); | |
// Handle class | |
$tags->add_class( 'is-active' ); | |
$tags->get_attribute( 'class' ); | |
$tags->remove_class( 'class' ); | |
// Return modified html | |
echo $tags->get_updated_html(); | |
// or | |
echo (string) $tags; | |
// Seek the next tag | |
$tags->next_tag(['tag_name' => 'IMG']); | |
$tags->get_tag(); // => 'IMG' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The official reference:
See also: