Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save glauberportella/fc08ccdb655f9d577e80 to your computer and use it in GitHub Desktop.
Save glauberportella/fc08ccdb655f9d577e80 to your computer and use it in GitHub Desktop.
Wordpress Filter - Youtube Video Resize to 16:9 using Bootstrap 3 Embed Responsive
<?php
//
// ADD TO YOUR THEME functions.php
// @author Glauber Portella <glauberportella@gmail.com>
//
/**
* Resize youtube videos
* Redim youtube videos URL that exists on content to be embed responsive using Bootstrap 3 embed responsive feature
* Needs theme with Bootstrap 3 support
*/
function d4w_youtube_responsive_filter($content) {
$replacement = '<div class="embed-responsive embed-responsive-16by9">$1</div>';
$regex = '#((<iframe.+?)(class="(.*?)")?(.+?src="https?:\/\/(?:www\.)?(?:youtube.com|youtu.be).*"[^>]+?></iframe>))#i';
$newContent = preg_replace_callback($regex, function($match) {
// replace class attr
$classRegex = '/class="(.*?)"/i';
$hasClass = preg_match($classRegex, $match[1]);
if (false !== $hasClass && $hasClass > 0) {
// class attr exists on iframe
$newIframe = preg_replace($classRegex, 'class="$1 embed-responsive-item"', $match[1]);
} else {
// no class attr exists on iframe
$replaceRegex = '/^<iframe/i';
$newIframe = preg_replace($replaceRegex, '<iframe class="embed-responsive-item"', $match[1]);
}
return $newIframe;
}, $content);
$newContent = preg_replace($regex, $replacement, $newContent);
return $newContent;
}
add_filter( 'the_content', 'd4w_youtube_responsive_filter' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment