<?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' );