Skip to content

Instantly share code, notes, and snippets.

@jeffreysfridge
Created February 21, 2020 22:28
Show Gist options
  • Save jeffreysfridge/71082144f934492b35cf20bcb789c111 to your computer and use it in GitHub Desktop.
Save jeffreysfridge/71082144f934492b35cf20bcb789c111 to your computer and use it in GitHub Desktop.
/*--------------------------------------------*/
/* Replace H Tags
/*--------------------------------------------*/
function get_inner_html( $node ) {
$innerHTML= '';
$children = $node->childNodes;
foreach ($children as $child) {
$innerHTML .= $child->ownerDocument->saveXML( $child );
}
return $innerHTML;
}
function my_added_page_content ( $content ) {
if ( is_page() ) {
$dom = new DOMDocument();
// $dom->loadHTML($content);
$dom->loadHTML('<?xml encoding="utf-8" ?>' . $content);
$xpath = new DOMXPath($dom);
$items = array('h1','h2','h3','h4','h5');
foreach ($items as $item) {
// $tags = $dom->getElementsByTagName($item);
$tags = $xpath->evaluate("//".$item);
foreach ($tags as $tag) {
$style = $tag->getAttribute('style');
$class = $tag->getAttribute('class');
// $newtag = $dom->createElement('div', htmlspecialchars($tag->nodeValue));
$newtag = $dom->createElement('div', get_inner_html($tag));
$newtag->setAttribute('class', $item.' '.$class);
if($style) $newtag->setAttribute('style', $style);
$tag->parentNode->replaceChild($newtag, $tag);
}
}
$dom = $dom->saveHTML();
// return $dom;
return htmlspecialchars_decode($dom);
} else {
return $content;
}
}
add_filter( 'the_content', 'my_added_page_content');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment