Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.