Last active
January 29, 2019 09:50
-
-
Save aaronsummers/76a793dfd772deb46302142673bd68a4 to your computer and use it in GitHub Desktop.
Youtube embed shortcode [youtube video=" "] < self closing shortcode
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function getYoutubeEmbedUrl($url) { | |
$shortUrlRegex = '/youtu.be\/([a-zA-Z0-9_]+)\??/i'; | |
$longUrlRegex = '/youtube.com\/((?:embed)|(?:watch))((?:\?v\=)|(?:\/))(\w+)/i'; | |
if (preg_match($longUrlRegex, $url, $matches)) { | |
$id = $matches[count($matches) - 1]; | |
} | |
if (preg_match($shortUrlRegex, $url, $matches)) { | |
$id = $matches[count($matches) - 1]; | |
} | |
return isset($id) ? $id : 'error'; | |
} | |
// Add Shortcode | |
function youtube_shortcode( $atts ) { | |
// Attributes | |
$atts = shortcode_atts( | |
array( | |
'video' => '', | |
), | |
$atts | |
); | |
return '<div class="video-wrapper"><iframe src="https://www.youtube.com/embed/' . getYoutubeEmbedUrl($atts['video']) . '" frameborder="0" allowfullscreen=""></iframe></div>'; | |
} | |
add_shortcode( 'youtube', 'youtube_shortcode' ); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
.video-wrapper { | |
iframe { | |
position: absolute; | |
top: 0; | |
left: 0; | |
width: 100%; | |
height: 100%; | |
} | |
height: 0; | |
padding-bottom: 56.3%; | |
position: relative; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment