Skip to content

Instantly share code, notes, and snippets.

@gh640
Created June 18, 2023 07:46
Show Gist options
  • Save gh640/9d9265056eee02bdfaca87ce7373d4f4 to your computer and use it in GitHub Desktop.
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
<?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'
@gh640
Copy link
Author

gh640 commented Jun 18, 2023

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment