Update 4/24/2013 - https://github.com/DashMedia/modx-youTubeId/blob/master/getYouTubeId.php This is a better solution.
We've been working on a new responsive website for Dan Schleck, a long time client, who needed a new website. He's been doing more youtube videos and I wanted an easy way to get the youtube ID but still easy for a client to input. I figured the url for the video would be easy enough.
I found a good article here on stack overflow on getting the youtube id from url. With Isaac's and Ryan's help we adapted it for MODx's awesome output filters.
<?php
/**
* get youtube video ID from URL
*
* @param string $url
* @return string Youtube video id or FALSE if none found.
*/
$url = $input;
if (!function_exists('youtube_id_from_url')) {
function youtube_id_from_url($url) {
$pattern =
'%^ # Match any youtube URL
(?:https?://)? # Optional scheme. Either http or https
(?:www\.)? # Optional www subdomain
(?: # Group host alternatives
youtu\.be/ # Either youtu.be,
| youtube\.com # or youtube.com
(?: # Group path alternatives
/embed/ # Either /embed/
| /v/ # or /v/
| /watch\?v= # or /watch\?v=
) # End path alternatives.
) # End host alternatives.
([\w-]{10,12}) # Allow 10-12 for 11 char youtube id.
$%x'
;
$matches = array ();
if (preg_match($pattern, $url, $matches)) {
return $matches[1];
}
return false;
}
}
echo youtube_id_from_url($url); # NLqAF9hrVbY
The Code / Snippet / Output Filter
An output filter is just a snippet that you run with the template variable, placeholder or other variable data as being the input, simple yet powerful. It reminds me of Unix scripting, little programs that do one job and pass it on.
I saved this as a snippet called youtubeId
Uses
I used it here to pull the HD Thumbnail into a grid listing with a getResources snippet call.
<img class="thumbnail" src="http://img.youtube.com/vi/[[+tv.youtube:youtubeId]]/hqdefault.jpg" /></a>
- You could use this same ID for grabbing video thumbnails with this hack
- Displaying the youtube video conditionally, with feeds, etc
Please post other ideas and suggestions below.

Comments (0)
Add a Comment