Skip to content

Instantly share code, notes, and snippets.

@aaronsummers
Last active January 29, 2019 09:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aaronsummers/76a793dfd772deb46302142673bd68a4 to your computer and use it in GitHub Desktop.
Save aaronsummers/76a793dfd772deb46302142673bd68a4 to your computer and use it in GitHub Desktop.
Youtube embed shortcode [youtube video=" "] < self closing shortcode
<?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' );
.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