Skip to content

Instantly share code, notes, and snippets.

@mustardBees
Created September 16, 2021 11:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mustardBees/1c1a3a7341748e8cf215cdf00548685f to your computer and use it in GitHub Desktop.
Save mustardBees/1c1a3a7341748e8cf215cdf00548685f to your computer and use it in GitHub Desktop.
<?php
/**
* Add a class to tags.
*
* @param string $html The HTML content.
* @param array $tags List of HTML tags to add a class to.
* @param string $class The class to add.
* @param bool $exception Optional. If the exception value has been defined, it'll take precedence.
*
* @return array|string|string[]|null
*/
function kanuka_add_class_to_tags( $html, $tags, $class, $exception = false ) {
if ( strlen( trim( $html ) ) <= 0 ) {
return;
}
libxml_use_internal_errors( true );
$dom = new DOMDocument( '1.0', 'utf-8' );
$head = '<head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /></head>';
$dom->loadHTML( $head . $html );
foreach ( $tags as $tag ) {
$elements = $dom->getElementsByTagName( $tag );
foreach ( $elements as $element ) {
// Bail if we already have an explicitly defined class value.
if ( $exception && false !== strpos( $element->getAttribute( 'class' ), $exception ) ) {
continue;
}
$element->setAttribute( 'class', trim( $element->getAttribute( 'class' ) . ' ' . $class ) );
}
}
$content = preg_replace( '/<\/?(!doctype|html|head|meta|body)[^>]*>/im', '', $dom->saveHTML() );
libxml_use_internal_errors( false );
return $content;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment