Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
<?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