Skip to content

Instantly share code, notes, and snippets.

@HowdyMcGee
Last active July 15, 2016 19:01
Show Gist options
  • Save HowdyMcGee/34cd801effb6e7a2f2d47f5f688b45f6 to your computer and use it in GitHub Desktop.
Save HowdyMcGee/34cd801effb6e7a2f2d47f5f688b45f6 to your computer and use it in GitHub Desktop.
WordPress - Add Background Color Styles From Spans To Parent Element
<?php
/**
* Pre Content Save
* - IF headers have span backgrounds
* - Put that style onto the parent header
*/
function set_header_backgrounds( $content ) {
if( empty( $content ) ) {
return $content;
}
$content = stripslashes( $content );
$htmlDOM = new DOMDocument();
$htmlDOM->loadHTML( mb_convert_encoding( stripslashes( $content ), 'HTML-ENTITIES', 'UTF-8' ) );
$xpath = new DOMXPath( $htmlDOM );
// Get all spans with style attributes
$elements = $xpath->query( '//h1//span[@style]|//h2//span[@style]|//h3//span[@style]|//h4//span[@style]|//h5//span[@style]|//h6//span[@style]' );
if( $elements->length ) { // IF we have spans with style attributes
foreach( $elements as $span ) {
$span_style = $span->getAttribute( 'style' ); // Grab the contents of the style attribute
$parent = $span->parentNode;
if( false !== strpos( $span_style, 'background' ) ) { // IF background is in the string
$parent_style = $span->parentNode->getAttribute( 'style' ); // Grab the parent node style attribute if it exists
$parent_style = rtrim( $parent_style, ';' ); // Remove ending `;` if it exists
$span_style = rtrim( $span_style, ';' ); // Remove ending `;` if it exists
$new_style = ( strlen( $parent_style ) > 0 ) ? "{$parent_style};" : '';
$new_style = "{$span_style};";
$parent_style = $span->parentNode->setAttribute( 'style', $new_style ); // Set style to header tag
$parent->textContent = $span->textContent;
}
}
}
$content = $htmlDOM->saveHTML();
$content = preg_replace( '~<(?:!DOCTYPE|/?(?:html|head|body))[^>]*>\s*~i', '', $content );
$content = addslashes( trim( $content ) );
return $content;
}
add_filter( 'content_save_pre', 'set_header_backgrounds' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment