Automatically center embedded videos

Mods and Stuff for WordPress
Post Reply
User avatar
syntax
Site Admin
Posts: 54
Joined: Tue Jan 06, 2009 9:25 pm

Automatically center embedded videos

Post by syntax » Wed Dec 17, 2014 6:03 pm

Only works for those uploaded locally and embedded by wordpress (which get a div with the "wp-video" class)

Code: Select all

//content filtering
function custom_filter_the_content( $content ) {
    $custom_content = $content;
	
	if (stripos($custom_content, 'class="wp-video"') !== FALSE) {
		$dom = new DOMDocument;
		libxml_use_internal_errors(true);
		$dom->loadHTML($custom_content, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
		libxml_use_internal_errors(false);
		$xpath = new DOMXPath($dom);
		$nodes = $xpath->query("//*[@class='wp-video']");
		$write_html = FALSE;
		foreach ($nodes as $node) {
			$div_style = $node->getAttribute('style');
			$i = stripos($div_style, 'width:');
			if ($i !== FALSE) {
				$x = stripos($div_style, 'px', $i+1);
				if ($x !== FALSE) {
					$video_width = trim(substr($div_style, $i+strlen('width:'), $x-$i-strlen('width:')));
					
					unset($element); $element = $dom->createElement('div');
					$element->setAttribute('style', 'width: '.$video_width.'px; margin: 0 auto 40px auto;');
					
					$node->parentNode->replaceChild($element, $node);
					$element->appendChild($node);
					$write_html = TRUE;
				}
			}
		}
		if ($write_html) { $custom_content = $dom->saveHTML(); }
	}

    return $custom_content;
}
add_filter( 'the_content', 'custom_filter_the_content' );

Post Reply